【发布时间】:2019-04-01 03:28:17
【问题描述】:
import { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
在上面的示例中,每当调用 setCount(count + 1) 时,都会发生重新渲染。我很想了解流程。
我尝试查看源代码。我在github.com/facebook/react 找不到任何useState 或其他挂钩的参考。
我通过npm i react@next 安装了react@next,并在node_modules/react/cjs/react.development.js 找到了以下内容
function useState(initialState) {
var dispatcher = resolveDispatcher();
return dispatcher.useState(initialState);
}
在回溯dispatcher.useState()时,我只能找到以下...
function resolveDispatcher() {
var dispatcher = ReactCurrentOwner.currentDispatcher;
!(dispatcher !== null) ? invariant(false, 'Hooks can only be called inside the body of a function component.') : void 0;
return dispatcher;
}
var ReactCurrentOwner = {
/**
* @internal
* @type {ReactComponent}
*/
current: null,
currentDispatcher: null
};
我想知道在哪里可以找到dispatcher.useState() 实现并了解它如何在调用 setStatesetCount 时触发重新渲染。
任何指针都会有所帮助。
谢谢!
【问题讨论】:
-
我相信这是
fiber的行为,所以说 Reacts 核心算法。他们将其描述为,React Fiber is an ongoing reimplementation of React's core algorithm.github.com/acdlite/react-fiber-architecture 我相信userState- 在fiber中创建对象和指针,当它的值发生变化时,它会触发重新渲染。这只是一个猜测,但我希望有类似的东西。 -
实际上,react 中的 hooks 使用 useState 来调用状态更新,类似于 setState。因此,无论何时更改状态,都会重新渲染组件。
标签: javascript reactjs react-hooks