如何使用useEffect处理监听多个变化?
我正在聆听多个价值观,并为这些价值观执行不同的操作。问题是我不知道阻止它们在第一次渲染时运行的最佳方法是什么。假设我有:
const [firstValue, setFirstValue] = useState();
const [secondValue, setSecondValue] = useState();
const [thirdValue, setThirdValue] = useState();
const [fourthValue, setFourthValue] = useState();
const [fifthValue, setFifthValue] = useState();
useEffect(()={
// action 1
},[firstValue, secondValue, thirdValue])
useEffect(()={
// action 2
},[fourthValue])
useEffect(()={
// action 3
},[fifthValue])
我查看了 isMounted = useRef(false)
示例,但只有当您只有 1 个额外的 useEffect
时它才有效。
I have multiple values I'm listening to and different actions to perform for those values. Problem is that I don't know what is the best way to prevent them from running on first render. Let's say I have:
const [firstValue, setFirstValue] = useState();
const [secondValue, setSecondValue] = useState();
const [thirdValue, setThirdValue] = useState();
const [fourthValue, setFourthValue] = useState();
const [fifthValue, setFifthValue] = useState();
useEffect(()={
// action 1
},[firstValue, secondValue, thirdValue])
useEffect(()={
// action 2
},[fourthValue])
useEffect(()={
// action 3
},[fifthValue])
I looked into isMounted = useRef(false)
example, but it works only if you have just 1 extra useEffect
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您假设您必须更新组件中第一个
useEffect
挂钩内的isMounted
引用。请记住,每个渲染周期都会按声明顺序调用所有钩子。如果您希望所有三个
useEffect
挂钩跳过初始渲染,则不要更新isMounted
引用,直到之后这三个挂钩都有机会更新至少运行一次。例子:
I think you are assuming you must update the
isMounted
ref within the firstuseEffect
hook in the component.Remember that all hooks are called each render cycle in the order they are declared. If you want all three
useEffect
hooks to skip the initial render then don't update theisMounted
ref until after all three have had a chance to run at least once.Example:
如果预期的功能是阻止在初始渲染期间执行 useEffect 内的代码,只需将代码保留在 if 条件内,该条件将检查每个状态的值是否不是该状态的初始值。
前任:
If the expected functionality is to prevent execution of a code inside useEffect during initial rendering, just keep the code inside an if condition which will check if each of the states have the values that is not the initial value of that state.
Ex: