`componentWillReceiveProps` 解释

IT技术 reactjs
2021-05-07 03:53:58

我最近想升级我对React 的认识,所以我从组件生命周期方法开始。让我好奇的第一件事就是这个componentWillReceiveProps因此,文档说它在组件接收新的(不一定更新的)props时被触发。在该方法中,我们可以比较它们并在需要时保存到状态中。

我的问题是:如果该组件(在 parent 内部render)的props 更改将触发该子组件的重新渲染,为什么我们需要该方法

4个回答

一个常见的用例是 state ( this.state) 更新,这可能是响应更新的 props 所必需的。

由于您不应该尝试通过this.setState()render函数中更新组件的状态,因此这需要在componentWillReceiveProps.

此外,如果某个 prop 被用作某个 fetch 函数的参数,您应该注意这个 propcomponentWillReceiveProps以使用新参数重新获取数据。

通常componentDidMount用作触发方法以获取某些数据的地方。但是如果你的容器,例如 UserData 没有卸载并且你改变了userIdprop,容器需要为相应的 userId 获取用户的数据。

  class UserData extends Component {
    componentDidMount() {
      this.props.getUser(this.props.userId);
    }

    componentWillReceiveProps(nextProps) {
      if (this.props.userId !== nextProps.userid) {
        this.props.getUser(nextProps.userId);
      }
    }

    render() {
      if (this.props.loading) {
        return <div>Loading...</div>
      }

      return <div>{this.user.firstName}</div>
    }
  }

这不是一个完整的工作示例。让我们想象一下,getUser调度终极版动作和终极版指定给组件userloadinggetUserprops。

它“用作”对传入 props 做出react的机会,以在渲染之前设置应用程序的状态。如果您在渲染后调用 setState ,您将无限地重新渲染,这就是您不允许这样做的原因,因此您可以改用 componentWillReceiveProps 。

但是......你的困惑超出了正确的范围,事实上他们正在弃用它和其他 Will-lifecycle hooks Discussion Deprecation 是正确的

  • 还有其他方法可以在没有大多数 Will-lifecycle 方法的情况下完成您想要做的事情,一种方法是在渲染后不要调用 setState,只需直接在渲染(或任何地方)中使用新传入的props来创建您的有状态值需要然后直接使用新值,然后您可以稍后设置状态以保留下一次迭代的引用 ex: this.state.someState = someValue,这将完成所有操作并且不会在无限循环中重新渲染组件。

以此为契机,在通过使用 this.setState() 更新状态来调用 render() 之前对 prop 转换做出react。旧的 props 可以通过 this.props 访问。在此函数中调用 this.setState() 不会触发额外的渲染。

看看这篇文章