首页 > 解决方案 > this.forceUpdate() 不重新渲染动态创建的组件

问题描述

假设所有不同的组件都已定义。

在我的反应组件中,我希望单击按钮触发TextBox在我动态创建的组件中附加一个新questions组件。当我用 测试按钮单击时forceUpdate(),aTextBox已成功附加到,questions但没有明显添加新TextBox元素。我通过 using 测试了组件是否实际上正在重新渲染,<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>
  );
}

标签: reactjs

解决方案


只有内部的项目this.state会被 React 正确监控是否应该发生重新渲染。使用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.


推荐阅读