javascript - ReactJS - this.state 中的数组在删除时正确更新,但结果直到后来的状态更改才呈现?

标签 javascript reactjs

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

相关文章:

javascript - 布局 Dojo 移动应用程序

javascript - Jquery:无法实时触发处理程序

javascript - React 中的 new Date().getFullYear()

javascript - 如何使用React数组映射方法将项目添加到特定的Id中

javascript - 类型错误 : Cannot read property 'map' of undefined - When tried to map values to cards

javascript - 为什么这个基本的 react-beautiful-dnd 示例没有动画

javascript - asp.net mvc - 如何使用 Javascript 创建多个 DropDownList

javascript - 使用 getJson 嵌套 Promise

javascript - Webpack Manifest Hashing - vendor 未进行哈希处理

reactjs - React useRef未定义