调用componentWillReceiveProps中的方法将显示陈旧道具的值

时间:2018-10-18 23:07:44

标签: reactjs

我知道componentWillRecieveProps在React 16+中已经被弃用,并且也知道React的对帐系统在大多数情况下是异步的,我认为是因为我在这里看到了这种行为。我只希望确认(或解决方案)能理解我的理解是否正确。

我有以下Child组件:

import React, { PureComponent } from "react";
import ReactDOM from "react-dom";

class Child extends PureComponent {

  componentWillReceiveProps(nextProps) {
    console.log("--nextprops--");
    console.log(nextProps);
    this.callMe();
  }

  callMe() {
    const { data } = this.props;
    console.log("--callme--", data);
    return <div>{data}</div>;
  }

  render() {
    console.log("--render--");
    return this.callMe();
  }
}

,并且此Parent组件中正在使用它。

class App extends PureComponent {
  constructor(props) {
    super(props);
    this.changeMe = this.changeMe.bind(this);
    this.state = {
      data: "ok"
    };
  }
  changeMe() {
    const dat = ["ok", "bye"];
    const randomize = parseInt(Math.random() > 0.5 ? 0 : 1);
    this.setState({
      data: dat[randomize]
    });
  }

  render() {
    return (
      <div>
        <button onClick={this.changeMe}> randomize </button>
        <Child data={this.state.data} />
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

https://codesandbox.io/s/ojo43r3xw9?expanddevtools=1

如果您运行上述应用程序并开始点击button,那么您会注意到行为符合预期,但是,如果您查看控制台,您会注意到在--render--上方, --callme--正在安慰旧的道具data,紧接着我们看到--callme--与预期数据。

现在,您可能只是告诉我在state组件中设置Child,然后在this.setState中将componentWillRecieveProps中的this.callMe用作回调处理程序-但这不是重点。

我很好奇的是,在callMe中立即调用componentWillReceiveProps时,不能保证props的值将被更新吗? /> 我现在唯一能想到的解决方案是将nextProps作为nextProps方法的参数,并从那里获取数据,但是我试图避免这种情况,只使用callMe检查道具的价值。

我确实尝试过在文档中查找是否提到了此行为,但是我找不到它,或者我看起来不够努力。

0 个答案:

没有答案