reactjs - 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>
);
}
解决方案
只有内部的项目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
.
推荐阅读
- vue.js - 使用 Vuex,为什么 mapGetters 不接受与 mapState 相同的语法?
- docker - PACT.Net 无法分配请求的地址
- javascript - 滚动条显示在其他内容上
- python - 较新版本的 Cython Numpy 扩展编译失败
- java - 从文本文件中读取行,并通过将行中的值写入新的文本文件来按平均值(平均值)对它们进行排序
- sonarqube - 从 VSTS Build 机器在 SonarQube 上发布代码指标时出现错误“Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF8”
- amazon-dynamodb - 用户表的 Dynamodb
- cordova-plugins - 在使用 Cordova 的 Android 中应用购买签名验证失败错误
- python - 使用python根据选择条件从json中提取值
- storefront - 如何在 Intershop7 中覆盖渲染 ISML 模板