【问题标题】:functional setState and props功能 setState 和道具
【发布时间】:2018-12-19 21:53:07
【问题描述】:

我很清楚为什么我们需要函数式 setState 以及它是如何工作的,例如

this.setState((prevState, props) => ...);

如上所述,您将先前的状态作为参数。

但是在参数中也要注意props。 Here遇到了关于function setState中props的解释:

此外,当更新依赖于道具时也适用。这些 当从父母那里收到道具时,也会变得陈旧 在异步执行开始之前,组件已更改。 因此,this.setState() 中的函数作为第二个参数 道具。

但是那个解释仍然没有点击到我。

有人可以举一个“道具”如何变得陈旧的例子吗?例如可能是一个代码 sn-p,它在使用 this.props 而不是 setState 采用的回调函数的参数中指定的“props”时演示了一个错误?

换句话说,我不明白为什么在功能 setState 中需要 props 参数,并且很高兴看到一个为什么需要它的示例。

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:
    class Children extends React.Component {
      state = {
        initial: true,
      };
    
      onClick = () => {
        this.props.handler();
        console.log(this.state.initial, this.props.initial); // true true
        this.setState((state, props) => {
          console.log(state.initial, props.initial); // true false
          console.log(this.state.initial, this.props.initial); // true true
        });
      };
      render() {
        console.log("render children", this.state.initial, this.props.initial);
        return <div onClick={this.onClick}>Click me</div>
      }
    }
    
    class Hello extends React.Component {
      state = {
        initial: true,
      };
    
      handler = () => {
        this.setState({initial: false});
      }
      render() {
        console.log("render parent", this.state.initial);
        return <Children initial={this.state.initial} handler={this.handler} />
      }
    }
    
    ReactDOM.render(
      <Hello name="World" />,
      document.getElementById('container')
    );
    

    在这个例子中,孩子将调用处理程序,该处理程序将改变父状态并更新他自己的状态。在回调中,你可以看到 props 和 this.props 是不同的:props 是新的值,而 this.props 是陈旧的。

    Demo here

    【讨论】:

      【解决方案2】:

      状态可能变得陈旧的方式也适用于道具。例如,假设有一个声明:

      this.setState((prevState, props) => ({foo: prevState.x + props.y} ));
      

      并且在异步 setState 执行开始之前,传递给组件的 prop x 被其父组件从 1 -> 2 更新。

      如果使用 this.props 而不是 props,则函数将使用 props 的旧值(调用 setState 时的值)执行。但是由于使用了函数式 setState,所以异步执行时的 props 永远是当时最新的 props。

      【讨论】:

        猜你喜欢
        • 2017-12-26
        • 2021-08-19
        • 1970-01-01
        • 1970-01-01
        • 2021-04-21
        • 2020-08-14
        • 2023-01-18
        • 1970-01-01
        • 2018-07-27
        相关资源
        最近更新 更多