Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[讨论] React dapp 模板默认禁用 StrictMode 是否更合适 ? #117

Closed
donotlb opened this issue Jun 14, 2022 · 4 comments · Fixed by #118
Closed

[讨论] React dapp 模板默认禁用 StrictMode 是否更合适 ? #117

donotlb opened this issue Jun 14, 2022 · 4 comments · Fixed by #118
Assignees
Milestone

Comments

@donotlb
Copy link
Contributor

donotlb commented Jun 14, 2022

启用 StrictMode 后,dev 环境下 useEffect(() => { ... }, []) 中的代码会执行 2 次, 感觉不便于调试.
另外, 我们也比较习惯在 useEffect 中 fetch data, 短期内应该也不会使用像下面 comment 里推荐的 React Query

参考: facebook/react#24502 (comment)

@LancelotLewis
Copy link
Collaborator

看了篇文章,描述 useEffect 的:https://mp.weixin.qq.com/s/h7GiH_s8e8wM0CDS_tF_3w
React 官方文档中也介绍 component 应该为 pure 的:https://beta.reactjs.org/learn/keeping-components-pure

综合下来的意思是:

  1. React 组件应该是一个纯函数,同样的输入一定要有同样的输出结果
  2. useEffect 是一个副作用函数,在代码中应该尽可能的不使用 useEffect,因为它会破坏 React 组件的纯度

在以上两点的基础之上,不管组件被重复挂载几次,都不会影响当前组件的渲染结果

虽然上面的解释是行得通的,但我个人感觉组件被挂载两次仍然是一个令人充满疑惑的情况,个人也赞成移除 StrictMode
这里有一个 Demo:https://stackblitz.com/edit/vitejs-vite-dgfgss?file=src/App.jsx

@LancelotLewis
Copy link
Collaborator

讨论结果:移除

@LancelotLewis
Copy link
Collaborator

mark
官方给出的请求方案是这样的:https://beta.reactjs.org/learn/synchronizing-with-effects#fetching-data

@donotlb
Copy link
Contributor Author

donotlb commented Jun 16, 2022

嗯,如果使用 strict mode, 感觉下面说的用一个第三方的请求库比较好,使用 ignore 变量这种方式,感觉有点难受 ...

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants