ReactJS-这个状态中的数组在删除时被正确更新,但结果是't,直到以后的状态发生变化

ReactJS - array in this.state is updated correctly on delete but result isn't rendered until later state changes?

本文关键字:状态 变化 结果是 更新 数组 删除 ReactJS-      更新时间:2024-04-12

我看到了这个问题的变体,但没有一个与我的问题相匹配。我正在显示一组文本字段,希望能够删除其中一个。当单击任何文本字段旁边的删除按钮时,数组中的最后一项将消失。然而,我已经检查了这个.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-儿童

当React调解关键儿童时,它将确保带有密钥的子项将被重新排序(而不是被丢弃)或销毁(而不是重复使用)。

考虑使用item.text作为密钥或特定于该项目的其他标识符。