前提:状态为prop的子组件如果在组件数组中,则不会在状态更改时重新呈现

问题描述

如果处于父组件状态的 currentQuestion 得到更新,它将以新状态重新呈现父组件。

问题是,从视图数组渲染的子组件似乎未获得作为prop传递的更新状态,因此不会重新渲染。

如果我直接在父级的渲染功能中(而不是从数组中)移动子级组件的渲染,一切都会按预期进行。

在这里没有发现问题,如果有人可以帮助的话,那太好了。

父母

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentQuestion: 0
    };

   // Child components should be stored in an array
   this.views = [
     <Questions
       currentQuestion={this.state.currentQuestion}
     />
   ];
 }

 render() {
   return <div className={style.quiz}>
     // Clicking this button,the parent gets rerendered properly with new state
     <button onClick={() => this.setState({currentQuestion: 3})}>Test</button>
     <div className={style.views}>
       {this.views.map(view => view)}
     </div>
   </div>;
 }

}

孩子

class Questions extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    // If the state of the parent component gets updated (button click),the props in here should update and therefore this should be called,which is not the case
    return <div>
      {this.props.currentQuestion}
    </div>
  }
}

解决方法

更新父级组件时不会更新子级组件,因为仅在运行父级的构造函数时才会实例化子级组件。

解决此问题的一种方法是确保每次父级更新(调用this.setState({currentQuestion:})时,子级组件也进行更新。

render() {
    return <div className={style.quiz}>
        ...
         <Questions currentQuestion={this.state.currentQuestion} />
        ...
     </div>;
}