【问题标题】:receiving props from App.js using componentWillRecieveProps使用 componentWillRecieveProps 从 App.js 接收道具
【发布时间】:2019-12-31 04:30:28
【问题描述】:
  • 在我的按钮组件的 app.js 中,我给了这个道具propTwo={"two"}
  • 但仍然 Button.js 没有在 componentWillReceiveProps 中打印
  • 你能告诉我如何使用 componentWillReceiveProps 方法接收道具
  • 你能告诉我如何在我的应用程序中使用 componentWillReceiveProps
  • 在下面提供我的代码 sn-p 和沙箱

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>
);

【问题讨论】:

  • 来自the documentation,强调我的:“React 不调用 UNSAFE_componentWillReceiveProps() 在安装过程中使用初始道具。它只调用此方法如果某些组件的道具可能会更新。”此外,正如至少一个答案所指出的那样,这种方法已被弃用,并将在下一版本的 React 中完全消失,因此学习它对自己没有任何好处。
  • 你能告诉我如何用componentWill Receive props实现
  • 没有。这是一个弃用方法。请注意所有大写字母开头的 UNSAFE。就像“我们正在摆脱这个东西,因为它容易出错并且会导致问题,所以不要使用它。永远。”
  • @JaredSmith 我有使用componentWillRecieveProps的代码库,所以我想通过一个例子来学习,你能更新我的沙箱吗:(
  • 除非您打算永远不再碰它,否则您将不得不更改您的代码库。你在这里问的事实意味着你实际上正在积极开发它。你将不得不在你的整个代码库中经历并改变它,我很抱歉,因为我去过那里,我知道这很糟糕。

标签: javascript html css reactjs redux


【解决方案1】:

你应该使用:

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

【讨论】:

  • 你能告诉我如何用componentWill Receive props来实现
  • 我有使用componentWillRecieveProps的代码库,所以我想用一个例子来学习,你能更新我的沙箱吗:(
【解决方案2】:

componentWillReceiveProps 已被弃用。

您可以使用componentDidUpdate

您可以通过在 componentDidUpdate 中访问 this.props 来访问更新的 props。

【讨论】:

  • 你能告诉我如何用componentWill Receive props实现
  • 我有使用componentWillRecieveProps的代码库,所以我想通过一个例子来学习,你能更新我的沙箱吗:(
猜你喜欢
  • 2019-06-08
  • 2023-01-22
  • 2019-09-10
  • 1970-01-01
  • 2021-06-07
  • 2020-04-08
  • 2022-06-17
  • 1970-01-01
  • 2018-01-13
相关资源
最近更新 更多