gpt4 book ai didi

reactjs - 仅当输入中的所有元素发生变化时,如何使 useEffect Hook 调用提供的效果?

转载 作者:行者123 更新时间:2023-12-04 05:41:13 26 4
gpt4 key购买 nike

我正在尝试将 UNSAFE_componentWillReceiveProps 转换为 Hook 。下面是使用CWRP的逻辑。

UNSAFE_componentWillReceiveProps(nextProps){
if (this.props.val1 !== nextProps.val1 && this.props.val2 !== nextProps.val2) {
// do something
}
}

有什么方法可以让 hook 仅在 val1 和 val2 更改时调用效果。

useEffect(() => {
// do something only when both inputs change
}, [val1, val2])

最佳答案

`我想你可以使用 react documents 中提到的自定义 Hook :

function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
}

function MyComponent({val1, val2}) {
let val1Prev = usePrevious(val1);
let val2Prev = usePrevious(val2);
useEffect(() => {
if(val1Prev !== val1 || val2Prev !== val2) {
// do whatever you want
}
})
}

另外,请注意react文档中的这句话:

It’s possible that in the future React will provide a usePrevious Hook out of the box since it’s a relatively common use case.

关于reactjs - 仅当输入中的所有元素发生变化时,如何使 useEffect Hook 调用提供的效果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54687852/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com