并且无法在互联网上找到答案。有没有办法在调用 useEffect 时做某事,如果没有调用 useEffect 则做其他事。像 if 语句?
喜欢:
**if** (useEffect(() => {
},[hello]) {
call a function } **else** {
call another function}
目标是在 var hello 更改时调用一个函数,而在 hello 未更改时调用另一个函数。谢谢。
答案 0 :(得分:0)
如果您在每次渲染时调用 useEffect
并创建几个自定义钩子来检查状态道具的先前值,您就可以实现这一点。
const Component = (props) => {
const hasHelloChanged = useHasChanged(hello);
useEffect(() => {
if (hasHelloChanged) {
// your code if hello has changed
} else {
// your code if it hasn't
}
});
return <>...</>;
};
const useHasChanged= (value) => {
const prevValue = usePrevious(value);
return prevValue !== value;
}
const usePrevious = (value) => {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
您可以查看此thread了解更多
答案 1 :(得分:0)
你不能完全按照你概述的去做,因为像 useEffect 这样的 React 钩子不能有条件地调用。
正如另一位发帖人所说,最好的办法是在每次渲染时调用 useEffect 并从 useEffect 内部触发分支操作。
答案 2 :(得分:0)
您是否尝试过使用两种不同的 useEffect 调用,一种是在 hello 更改时,另一种是在相关的其他属性更改时。 例如;
<块引用>useEffect(() => { // desired action }), [hello]);
每当hello的值改变时,总是会调用上面的效果,而;
useEffect(() => {
// desired action
}), [theOtherPropertyInQuestion]);
将始终在 theOtherPropertyInQuestion 的值发生变化时被调用 如果它们不是互斥的,您可以使用
useEffect(() => {
// desired action
}), [hello, theOtherPropertyInQuestion]);