0

React 文档讲述了很多关于setState()异步和这个特性的后果的信息。
特别是,它说

因为 this.props 和 this.state 可能是异步更新的,所以你不应该依赖它们的值来计算下一个状态。

它还提供了很好的例子,为什么依赖this.props可能(并且将会)破坏你的代码。其中之一(从这里):

// multiple call like this
this.setState({ quantity: state.quantity + 1 });

// may be batched and will result in the equivalent of
Object.assign(
    previousState,
    { quantity: state.quantity + 1 },
    { quantity: state.quantity + 1 },
    ...
 );

在理解状态更新的异步性质时,这些示例非常具有说明性和帮助性。

不幸的是,我找不到任何关于依赖this.props状态更新的类似示例。
有人可以帮我吗?我希望看到最少的说明性代码,但如果你有一个巨大的真实示例,它也会很棒。:)

谢谢你。

4

1 回答 1

1

您可以将函数作为第一个参数传递给setState. 该函数获取状态和道具作为参数,您从该函数返回的对象将用于更新状态。

例子

this.setState((state, props) => ({ counter: state.counter + props.step }))

看到这一点很重要的一种方法是,当您在子组件中调用可能导致父组件更改给子组件的道具时。如果您引用,this.props您将获得一个过时的值。

例子

class Counter extends React.Component {
  state = {
    counter: 0
  };

  onClick = () => {
    this.props.onIncrement();

    this.setState({ counter: this.state.counter + this.props.step });
    // This works
    // this.setState((state, props) => ({ counter: state.counter + props.step }));
  };

  render() {
    return <button onClick={this.onClick}>{this.state.counter}</button>;
  }
}

class App extends React.Component {
  state = {
    step: 0
  };

  incrementStep = () => {
    this.setState(({ step }) => ({ step: step + 1 }));
  };

  render() {
    return <Counter step={this.state.step} onIncrement={this.incrementStep} />;
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

于 2019-03-13T10:39:41.553 回答