使用componentWillRecieveProps从App.js接收道具

时间:2019-08-27 02:49:02

标签: javascript html css reactjs redux

  • 在我的按钮组件app.js中,我给了这个道具propTwo={"two"}
  • 但Button.js仍然没有在componentWillReceiveProps内部打印
  • 您能告诉我如何使用componentWillReceiveProps方法接收道具吗?
  • 您能告诉我如何在我的应用程序中使用componentWillReceiveProps
  • 在下面提供我的代码段和沙箱

https://codesandbox.io/s/hopeful-villani-xyikq

class Button extends Component {
  componentWillReceiveProps(nextprops) {
    console.log("componentWillReceiveProps nextprops--->", nextprops);
  }
  render() {
    return (
      <div>
        <button
          onClick={() => {
            // getPosts(channel);
            //  getAlert();
          }}
          className="btn btn-primary btn-lg btn-block"
        >
          Get top news
        </button>
      </div>
    );
  }
}

App.js

const App = () => (
  <div>
    <RecentChannelItem />
    <ChannelsField propOne={"one"} />
    <Button propTwo={"two"} />
    <TopNews />
  </div>
);

2 个答案:

答案 0 :(得分:1)

componentWillReceiveProps已被弃用。

您可以使用componentDidUpdate

您可以通过访问componentDidUpdate内部的this.props来访问更新的道具。

答案 1 :(得分:1)

您应该使用:

static getDerivedStateFromProps(nextprops) {
    console.log("componentWillReceiveProps nextprops--->", nextprops);
  }