我的组件有两个 Rect.useEffect
钩子(Hook)
const Example = ({ user }) => {
React.useEffect(() => {
autorun(() => {
console.log("inside autorun", user.count);
});
});
// Only runs once
React.useEffect(() => {
console.log("Why not me?");
});
return <Observer>{() => <h1>{user.count}</h1>}</Observer>;
};
我使用mobx
更新此组件。它被正确地重新渲染。但是“Why not me?”
只打印一次。
By default, effects run after every completed render
这意味着 console.log("Why not me?");
也应该在每次更新 prop user
时运行。但事实并非如此。控制台输出是这样的
这种明显的不一致背后的原因是什么?
我的完整代码可以在这里查看
最佳答案
在 Mobx 中,就像提供渲染函数回调的 Observer 组件一样,autorun 函数也独立于 React 生命周期执行。
发生此行为是因为您将用户计数作为可观察变量。
根据 mobx-react 文档
Observer is a React component, which applies observer to an anonymous region in your component. It takes as children a single, argumentless function which should return exactly one React component. The rendering in the function will be tracked and automatically re-rendered when needed.
和 mobx 文档
When
autorun
is used, the provided function will always be triggered once immediately and then again each time one of its dependencies changes.
您可以通过直接登录功能组件来确认此行为,并且您将观察到该组件仅呈现一次
编辑:
回答你的问题
If I change
useEffect
to thisReact.useEffect(autorun(() => {console.log("inside autorun", user.count)}));
basically remove anonymous function from
useEffect
and just pass autorun directly, then it is run only once. Why is it so? What's the difference?
不同之处在于,autorun
返回一个disposer 函数
,该函数在运行时将处置autorun
并且不再执行它。
来自文档:
The return value from autorun is a disposer function, which can be used to dispose of the autorun when you no longer need it.
现在发生的情况是,由于 useEffect 执行运行时提供给它的回调,因此执行的回调是 autorun 返回的 disposer
函数,它本质上取消了自动运行。
关于reactjs - 为什么 useEffect 不会在每次渲染时触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55451484/