Reactjs 此.forceUpdate()无法重新呈现动态创建的组件
假设已经定义了所有不同的组件 在我的react组件中,我希望单击按钮触发在动态创建的Reactjs 此.forceUpdate()无法重新呈现动态创建的组件,reactjs,Reactjs,假设已经定义了所有不同的组件 在我的react组件中,我希望单击按钮触发在动态创建的问题组件中添加新的文本框组件。当我用forceUpdate()测试按钮点击时,一个TextBox被成功添加到问题中,但没有明显添加新的TextBox元素。我使用Random number:{Math.Random()}测试了组件是否真的在重新渲染,结果发现组件正在这样做,因为每次我按下按钮时,数字都会改变 有什么做错了吗 constructor (props) { super(props); this.q
问题组件中添加新的文本框组件。当我用forceUpdate()
测试按钮点击时,一个TextBox
被成功添加到问题
中,但没有明显添加新的TextBox
元素。我使用Random number:{Math.Random()}
测试了组件是否真的在重新渲染,结果发现组件正在这样做,因为每次我按下按钮时,数字都会改变
有什么做错了吗
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.questions.push();
this.createTextBox=this.createTextBox.bind(this);
this.loadTextBox=this.loadTextBox.bind(this);
}
createTextBox(){
this.questions.push();
这个.forceUpdate();
}
loadTextBox(){
返回(这个问题);
}
render(){
返回(
随机数:{Math.Random()}
{this.loadTextBox()}
文本框
);
}
只有此状态中的项目才能通过React正确监控是否应重新提交。使用this.forceUpdate
不会检查this.questions
是否已更改
使用this.questions
作为this.state.questions
。执行此操作时,请不要变异此.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);
}
构造函数(道具){
超级(道具);
此.state={
问题:[]
}
this.createTextBox=this.createTextBox.bind(this);
this.loadTextBox=this.loadTextBox.bind(this);
}
createTextBox(){
const newQuestions=[…this.state.questions,]
//或者你可以使用
//const newQuestions=this.state.questions.concat()
this.setState({questions:newQuestions})
}
loadTextBox(){
返回(本.状态.问题);
}
需要注意的一点是,this.forceUpdate
几乎不需要。如果您发现自己正在使用它,那么您正在以一种不理想的方式编写代码。关于如何分配密钥,我对您的代码进行了一些修改。您应该检查更新的唯一原因是this.state
中的某些内容是否已更改,这涉及使用this.setState
您的意思是视觉上有新的文本框,但dom中没有新的文本框?感谢您的建议和帮助!工作得很有魅力。@Jemsavy总是碰巧帮忙。祝你的应用程序好运