javascript - 使用 React 正确更新组件状态中的数组

标签 javascript reactjs

<分区>

我正在学习 React 并试图了解如何更好地处理使用数组更新组件的状态。下面是我在组件的 componentWillMount() 上调用的函数,用于生成稍后在该父组件中呈现的组件:

  generateThings = () => {
    let newThings = [];
    for (let j = 0; j < this.state.numberOfThings; j++) {
      const pos = this.generatePosition(1, 1);
      const thingComp = <Thing key={j} position={pos} />;
      newThings.push(thingComp);
    }
    this.setState({
      things: newThings
    });
  };

我认为更好的方法是 push() 直接到状态字段 (this.state.things.push(thingComp);) 而不是存储在一个看起来更困惑的临时变量中。但这似乎不会触发 UI 更新,所以我猜这是这样做的方法,但我不确定。

最佳答案

你所做的是正确的。

当您调用 setState 时,它会导致组件重新呈现:根据 React Docs

setState() enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state

Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.

如果您需要更新/推送到现有的 things 数组:

let things = this.state.things.slice(); // make a copy

//push or do whatever to the array
things.push(thingComp)

this.setState({ things: newThings });

关于javascript - 使用 React 正确更新组件状态中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48014893/

相关文章:

javascript - 拖动文件时更改元素的 CSS 属性

javascript - 4 次查询后更新 Dojo 图表

javascript - 使用 ES6 编写的 React 组件获取 "cannot read property of undefined"

reactjs - 在 typescript 泛型类型声明中遇到问题

html - 'position: absolute' 的祖 parent 、 parent 和子女管理问题

javascript - 使用 node.js 作为 WebRTC 对等点?

javascript - 使用带有正文和 URL 参数的 JQuery 的 AJAX POST 请求

Chrome 阻止了 Javascript 打印

javascript - 我们如何根据表列对 createEntityAdapter 的实体进行排序?

javascript - 如何将字符串渲染为自定义 React 组件?