我最近想升级我对React 的认识,所以我从组件生命周期方法开始。让我好奇的第一件事就是这个componentWillReceiveProps。因此,文档说它在组件接收新的(不一定更新的)props时被触发。在该方法中,我们可以比较它们并在需要时保存到状态中。
我的问题是:如果该组件(在 parent 内部render)的props 更改将触发该子组件的重新渲染,为什么我们需要该方法?
我最近想升级我对React 的认识,所以我从组件生命周期方法开始。让我好奇的第一件事就是这个componentWillReceiveProps。因此,文档说它在组件接收新的(不一定更新的)props时被触发。在该方法中,我们可以比较它们并在需要时保存到状态中。
我的问题是:如果该组件(在 parent 内部render)的props 更改将触发该子组件的重新渲染,为什么我们需要该方法?
一个常见的用例是 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调度终极版动作和终极版指定给组件user,loading和getUserprops。
它“用作”对传入 props 做出react的机会,以在渲染之前设置应用程序的状态。如果您在渲染后调用 setState ,您将无限地重新渲染,这就是您不允许这样做的原因,因此您可以改用 componentWillReceiveProps 。
但是......你的困惑超出了正确的范围,事实上他们正在弃用它和其他 Will-lifecycle hooks Discussion Deprecation 是正确的。
this.state.someState = someValue,这将完成所有操作并且不会在无限循环中重新渲染组件。以此为契机,在通过使用 this.setState() 更新状态来调用 render() 之前对 prop 转换做出react。旧的 props 可以通过 this.props 访问。在此函数中调用 this.setState() 不会触发额外的渲染。
看看这篇文章