Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

163
Visualizações
¿Cómo se agregan valores de los estados de un componente secundario en React?

Parent un componente principal y varios componentes Child , cada uno de los cuales carga un value asíncrono desde una API cuando se montan. Me gustaría mostrar el total de estos valores en el Parent . ¿Cuál es el mejor patrón para hacer esto en React?

 export class Parent extends React.Component { constructor(props) { super(props); } render() { return ( <> <Child name='nick' /> <Child name='lucile' /> <Child name='buster' /> <span>{ TBD: Total of each Child's state.value ??? }</span> </> ) }
 export class Child extends React.Component { constructor(props) { super(props); this.state = { value: 0 } } async componentDidMount(){ let response = await axios.get(`https://getvaluefromapi/{this.props.name}`) this.setState({value: response.data.value}) } render() { return (<span>{this.state.value}<span>) } }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

import React from "react"; import Child from "../components/child"; class Parent extends React.Component { //State state = {}; getValue = (user, value) => { this.setState({ [user]: value }); }; render() { return ( <div> <Child name="nick" getValue={this.getValue} /> <Child name="buster" getValue={this.getValue} /> <Child name="lucile" getValue={this.getValue} /> <div>{this.state.nick + this.state.buster + this.state.lucile}</div> </div> ); } } export default Parent; import React, { Component } from "react"; class Child extends Component { constructor(props) { super(props); this.state = { value: 0, }; } async componentDidMount() { let response = await axios.get(`https://getvaluefromapi/{this.props.name}`); this.setState({ value: response.data.value }); this.props.getValue(this.props.name, response.data.value); } render() { return <p>{this.state.value}</p>; } } export default Child;

Es enteramente su elección cómo desea continuar desde aquí. Puede agregarlos todos en un componenteDidUpdate() a un valor total. O los muestra agregados directamente en el dom.

También puede pasar una función directamente desde el elemento principal que agregaría el totalValue actual con cada valor independiente, sin embargo, no sé si eso funcionaría debido a la secuenciación y las representaciones simultáneas de los elementos secundarios. Si todos los elementos secundarios se procesan al mismo tiempo, es posible que obtenga valores incorrectos en el valor total. Sin embargo, creo que así es como se vería esa opción.

 import React from "react"; import Child from "../components/child"; class Parent extends React.Component { //State state = { totalValue: 0, }; getValue = (value) => { this.setState({ totalValue: this.state.totalValue + value }); }; render() { return ( <div> <Child name="nick" getValue={this.getValue} /> <Child name="buster" getValue={this.getValue} /> <Child name="lucile" getValue={this.getValue} /> <div>{this.state.totalValue}</div> </div> ); } } export default Parent; import React, { Component } from "react"; class Child extends Component { constructor(props) { super(props); this.state = { value: 0, }; } async componentDidMount() { let response = await axios.get(`https://getvaluefromapi/{this.props.name}`); this.setState({ value: response.data.value }); this.props.getValue(response.data.value); } render() { return <p>{this.state.value}</p>; } } export default Child;
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda