Nin*_*liu 8 javascript reactjs react-hooks
让我们从我最喜欢的 JavaScript 表达式开始:
[]==[] // false
Run Code Online (Sandbox Code Playgroud)
现在,让我们说一下React 文档关于跳过副作用的内容:
如果某些值在重新渲染之间没有改变,你可以告诉 React 跳过应用效果。为此,将数组作为可选的第二个参数传递给 useEffect:
Run Code Online (Sandbox Code Playgroud)useEffect(() => {/* only runs if 'count' changes */}, [count])
现在让我们考虑以下行为让我挠头的组件:
[]==[] // false
Run Code Online (Sandbox Code Playgroud)
useEffect(() => {/* only runs if 'count' changes */}, [count])
Run Code Online (Sandbox Code Playgroud)
添加“apple”时,这是在控制台中记录的内容:
// on first render
Fruit changed to
Fruits changed to
// after each keystroke of 'apple'
Fruit changed to a
Fruit changed to ap
Fruit changed to app
Fruit changed to appl
Fruit changed to apple
// ater clicking on 'add'
Fruits changed to apple
Run Code Online (Sandbox Code Playgroud)
我不明白中间部分。每次击键后,fruits从[]到[],如果它们指的是不同的对象,则在 JS 中是不一样的。因此,我预计Fruits changed to会记录一些日志。所以我的问题是:
React 用来决定是否跳过效果钩子的确切对象比较过程是什么?
用于比较对象的函数实际上是Object.ismethod的 polyfill 。你可以在源代码中看到它:
https://github.com/facebook/react/blob/master/packages/shared/objectIs.js
这是一个prevDeps与nextDeps内比较的函数useEffect实现:
顺便提一下,Object.is被提及作为比较algorhitm在文档上的钩子API部分,下useState。