this.forceUpdate()不会重新呈现动态创建的组件

时间:2018-05-13 04:00:43

标签: reactjs

假设已经定义了所有各种组件。

在我的react组件中,我希望单击按钮以触发在我动态创建的TextBox组件中附加新的questions组件。当我点击按钮点击forceUpdate()时,TextBox已成功附加到questions,但没有明显添加新的TextBox元素。我通过使用<h4>Random number : {Math.random()}</h4>来测试组件是否实际上是重新渲染的,结果是组件正在这样做,因为每次按下按钮时数字都会改变。

做错了什么?

constructor (props) {
  super(props);
  this.questions = [];
  this.questions.push(<TextBox key={this.questions.length}/>);
  this.createTextBox = this.createTextBox.bind(this);
  this.loadTextBox = this.loadTextBox.bind(this);
}

createTextBox() {
  this.questions.push(<TextBox key={this.questions.length}/>);
  this.forceUpdate();
}

loadTextBox() {
  return (this.questions);
}

render() {
  return(
    <div>
      <h4>Random number : {Math.random()}</h4>
      {this.loadTextBox()}
      <ButtonToolbar className="add-question">
        <DropdownButton bsSize="large" title="Add" id="dropdown-size-large" dropup pullRight>
          <MenuItem eventKey="1" onClick={this.createTextBox}>Text Box</MenuItem>
        </DropdownButton>
      </ButtonToolbar>
    </div>
  );
}

1 个答案:

答案 0 :(得分:0)

React是否正确监控this.state内的项目是否应该进行重新渲染。使用this.forceUpdate不会检查this.questions是否已更改。

this.questions用作this.state.questions。执行此操作时,请勿改变this.state.questions。而是制作一份新副本并在其上使用this.setState

constructor (props) {
  super(props);
  this.state = {
    questions: [<TextBox key={0}/>]
  }
  this.createTextBox = this.createTextBox.bind(this);
  this.loadTextBox = this.loadTextBox.bind(this);
}

createTextBox() {
  const newQuestions = [...this.state.questions, <TextBox key={this.questions.length}/>]
  // or you can use 
  // const newQuestions = this.state.questions.concat(<TextBox key={this.questions.length + 1}/>)
  this.setState({questions: newQuestions})
}

loadTextBox() {
  return (this.state.questions);
}

需要注意的一点是,this.forceUpdate几乎不需要。如果您发现自己使用它,那么您将以不理想的方式编写代码。我对您的代码进行了一些关于如何分配密钥的修改。您应该检查更新的唯一原因是this.state中的某些内容是否已更改,包括使用this.setState

相关问题