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

137
Visualizações
Parent scope not triggering child rerender in React

i have a prent comp and a child cmponent. as follows

parent

export class ExpressionMenu extends Component {
 
  constructor(props) {
    super(props)
  }

  state = {
    apiArray: [],
  }

  updateStateFromChild = (arrayType, propertyType, value) => {
    let { apiArray } = this.state
    let currentArray = []
    let idx = apiArray.findIndex((q)  => q.id === id)
    currentArray = apiArray
    
    switch(propertyType) {
      case 'updateObject': {
        currentArray = value
        break;
      }
    }

    this.setState({
      apiArray: currentArray 
    })
  }
  

  render () {
    const {
     apiArray
    } = this.state

    return (
      <React.Fragment>
        <div >
          <div>
            <ApiPanel 
                apiArray={apiArray} 
                updateStateFromChild={this.updateStateFromChild} 
            />
            
         </div>  
        </div>
      </React.Fragment>
    )
  }
}  
  ExpressionMenu.propTypes = {
    styleOverride: PropTypes.object,
    eventHandler: PropTypes.func,
  };
  
  export default ExpressionMenu;

child


export class ApiPanel extends Component {
  constructor(props) {
    super(props),
  }

  removeApi = (id) => {
    let { apiArray } = this.props
    apiArray = apiArray.filter((q) => q.id !== id);
    this.props.updateStateFromChild('api', 'updateObject', apiArray)
  };

  addApi = () => {
    let { apiArray } = this.props
    const id = uniqid();
    let obj = {}
    obj.id = id
    apiArray.push(obj)
    this.props.updateStateFromChild('api', 'updateObject', apiArray)
  };

  render() {
    const { apiArray } =  this.props
   
    return (
      <React.Fragment>
        {
          apiArray.map((apiObj, i) =>
           <div key={i} >
            <span onClick={() => this.removeApi(apiObj.id) } className={[classes.deleteRow,'material-icons'].join(' ')}>
                close
              </span>
              
                <div>
                  <label><b>Hi</b></label>
                </div>
              
               <div onClick={this.addApi}>+Add Api</div>
        }
       
      </React.Fragment>
    )
  }
}

ApiPanel.propTypes = {
  apiArray: PropTypes.array,
  updateStateFromChild: PropTypes.func
}

export default ApiPanel

Now when i call addApi(), it updates the parent but doesnt rerenders the child. But when i call removeApi() , it updates parent as well as rerenders the child component properly.

in the first case when i manually reload the componnt i can see the change.

Dont understand why this is happening

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Try to change your addApi function.

addApi = () => {
    let { apiArray } = this.props
    this.props.updateStateFromChild('api', 'updateObject', [...apiArray, {id : uniqid()} ])
  };

You need to return an enriched copy of your array

about 4 years ago · Juan Pablo Isaza Relatório

0

Whenever we are updating the stating using arrays, objects. We need to always create a new array [...array], a new object {...obj}. Because if we update value in the array or obj without creating it won't change the reference value hence it assumes the state is not update and won't re-render.

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