【问题标题】:Properly updating arrays in component state using React [duplicate]使用 React 正确更新组件状态中的数组
【发布时间】:2018-06-09 10:32:42
【问题描述】:

我正在学习 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 语法。例如:this.setState((prevState) =&gt; { prevState.things.push(...); return prevState; })。请注意,setState 调用之外的变异状态不会触发更新。

标签: javascript reactjs


【解决方案1】:

另外,如果你愿意,你可以设置状态而不用 push 和 slicing 到不同的数组。

代码沙盒:https://codesandbox.io/s/jn8w8w34n3

the additional array solution is commented

【讨论】:

    【解决方案2】:

    你所做的是正确的。

    当你调用setState时,它会导致组件重新渲染:根据React Docs

    setState() 将组件状态的更改排入队列并告诉 React 这个组件及其子组件需要重新渲染 更新状态

    永远不要直接改变 this.state,因为之后调用 setState() 可能 替换您所做的突变。把 this.state 当作是 不可变。

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

    let things = this.state.things.slice(); // make a copy
    
    //push or do whatever to the array
    things.push(thingComp)
    
    this.setState({ things: newThings });
    

    【讨论】:

      猜你喜欢
      • 2020-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-15
      • 1970-01-01
      • 2020-10-19
      相关资源
      最近更新 更多