我看到过这个问题的变体,但没有一个与我的问题相符。我正在显示一组文本字段并希望能够删除其中一个。单击任何文本字段旁边的删除按钮时,数组中的最后一项将消失。但是,我检查了 this.state 并删除了正确的项目,只是从呈现的数组中取出了错误的项目。当我单击一个隐藏文本字段然后取消隐藏的按钮时,数组已修复并显示已删除的正确项目。为什么会这样?状态已更新为我想要删除的内容,但它似乎呈现了状态以外的内容。我试过在 setState
回调中使用 this.forceUpload();
但这并不能解决问题。
我已经包含了代码中的一些相关片段,如果需要还可以包含更多片段。
export class Questions extends React.Component {
constructor(props) {
super(props);
this.state = {
...
choices: []
...
};
}
deleteChoice = (index) => {
let tempChoices = Object.assign([], this.state.choices);
tempChoices.splice(index, 1);
this.setState({choices: tempChoices});
};
renderChoices = () => {
return Array.from(this.state.choices).map((item, index) => {
return (
<li key={index}>
<TextField defaultValue={item.text} style={textFieldStyle} hintText="Enter possible response..."
onChange={(event) => { this.handleChoice(event, index); }}/>
<i className="fa fa-times" onClick={() => { this.deleteChoice(index); }}/>
</li>
);
});
};
render() {
let choices = (
<div>
<div className="choices">Choices</div>
<ul>
{this.renderChoices()}
<li>
<RaisedButton label="Add another" style={textFieldStyle} secondary
onClick={() => { this.addChoice(); }}/>
</li>
</ul>
</div>
);
return (
{choices}
);
}
}
感谢您的帮助,这真是令人沮丧。
最佳答案
您需要在 renderChoices
函数中使用数组索引以外的键。您可以在 React 的文档中阅读更多关于为什么会出现这种情况的信息:
https://facebook.github.io/react/docs/multiple-components.html#dynamic-children
When React reconciles the keyed children, it will ensure that any child with key will be reordered (instead of clobbered) or destroyed (instead of reused).
考虑使用 item.text
作为键或特定于该项目的其他标识符。
关于javascript - ReactJS - this.state 中的数组在删除时正确更新,但结果直到后来的状态更改才呈现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36509730/