reactjs - 为什么 useEffect 不会在每次渲染时触发?

标签 reactjs react-hooks mobx-react

我的组件有两个 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?”只打印一次。

根据official docs

By default, effects run after every completed render

这意味着 console.log("Why not me?"); 也应该在每次更新 prop user 时运行。但事实并非如此。控制台输出是这样的

这种明显的不一致背后的原因是什么?

我的完整代码可以在这里查看

Edit mobx-useEffect query

最佳答案

在 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 this

React.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/

相关文章:

javascript - 在 ReactJS 中检查数组是否有数据或为空时遇到问题

reactjs - react native : header styles in navigationOptions not working

javascript - 另一种情况是组件的状态发生变化但组件似乎没有变化

javascript - React Hooks ref.current 在测试期间未定义

reactjs - React Context 和 Hooks API 的 enzyme 错误

reactjs - React Mobx - 商店更改后组件未更新

reactjs - MobX + React Router 4 + @withRouter 总是在路由改变时重新渲染

reactjs - 解析 JSON babel 失败时出错

javascript - 尝试访问 S3 时呈现比之前渲染更多的钩子(Hook)

javascript - 导入 mobx 的方式之间的区别