Reactjs 我们如何使用useEffect更改多个道具的值
我们如何识别功能组件中的道具变化?。这里是示例代码。您能帮助我使用useEffect或任何其他方式将此componentDidUpdate方法转换为功能组件吗Reactjs 我们如何使用useEffect更改多个道具的值,reactjs,react-hooks,Reactjs,React Hooks,我们如何识别功能组件中的道具变化?。这里是示例代码。您能帮助我使用useEffect或任何其他方式将此componentDidUpdate方法转换为功能组件吗 componentDidUpdate(prevProps){ if(prevProps.props1 !== this.props.props1){ //1st Function call } if(prevProps.props2 !== this.props.props2){ //2nd Func
componentDidUpdate(prevProps){
if(prevProps.props1 !== this.props.props1){
//1st Function call
}
if(prevProps.props2 !== this.props.props2){
//2nd Function call
}
}
//-----------------
useEffect(()=>{
},[props1, props2])
如果您想在不同道具更改时调用不同的函数,则可以对每个道具更改使用多个
useffect
请尝试以下操作:-
useEffect(()=>{
// function call when props1 change
},[props1])
useEffect(()=>{
// function call when props2 change
},[props2])
您可以为此执行两个单独的
useffect
。您不必将它放在一个useffect
上,因为很难识别哪个州进行了更新
useffect(()=>{
},[props1]);
useffect(()=>{
},[props2]);
最简单的解决方案是使用多个useEffect调用,每个属性调用一个:
useEffect(()=>{
// Something when props1 changes
},[props1])
useEffect(()=>{
// Something when props2 changes
},[props2])
如果您确实需要一个组合的useEffect(例如,如果存在一些共享逻辑),您可以将useEffect与
改进的方法:
这回答了你的问题吗?虽然这种方法非常吸引人,但我想知道渲染是否可以加入多个更新请求。例如,如果prevProps1发生了变化,并且props1也发生了变化,那么在两次不同的更新中会触发两次渲染吗?这个问题可能与
usePrevious
无关,我很抱歉。好的,我想答案是否定的,可能这里已经回答了,setProp1
被调用,然后两个效果都将在渲染后更新。usePrevious不会触发重新渲染。只有当props1更改而不是PREVISPROPS1更改时,才会触发效果。因此,您不必担心双重重新渲染。
const prevProps1 = usePrevious(props1);
const prevProps2 = usePrevious(props2);
useEffect(() => {
// compare props1 with prevProps1 and props2 with prevProps2
}, [props1, props2]);
let {current: {p1, p2} = {}} = useRef()
useRef(() => {
p1 = props1 // check with if (p1!=props1)
p2 = props2 // check with if (p2!=props2)
}, [p1,p2]) // run effect when p1 or p2 change
// basically states when props1 or props2 changes.