我开始学习 ReactJS ,我想知道使用 componentWillReceiveProps 的场景是什么?使用目的是什么? 目前我正在使用没有它的道具,有没有影响?
答案 0 :(得分:2)
如果您想对子组件采取措施以响应道具更改,则componentWillReceiveProps
应该是正确的候选人。例如,当您有一个用户组件,该组件调用并使用API来基于其父级提供的ID来获取用户详细信息时,并且只要prop ID发生更改,您都希望再次触发API调用并重新呈现该API。更新的视图。
但是,在每个父级重新渲染时都调用componentWillReceiveProps,而不仅是更改道具,因此,在使用它时,必须在之前和currentProps之间提供条件检查,例如
componentWillReceiveProps(nextProps) {
if(nextProps.id !== this.props.id) {
//API call goes here
}
}
但是,从v16开始,不鼓励使用componentWillReceiveProps
,而是将其用法分为componentDidUpdate
,在这里您可以进行API调用和getDerivedStateFromProps or memoized functions or key updates
以便基于状态更改更改道具。
请检查componentWillReceiveProps vs getDerivedStateFromProps
了解更多详细信息
答案 1 :(得分:0)
如果您的组件接受一些道具,并且如果您更改了这些道具,那么您希望进行一些业务逻辑或状态更改,则componentWillReceiveProps
是该逻辑应该使用的生命周期方法,因为每次道具更改时{{ 1}}。