Ada*_*leb 9 reactjs react-hooks
我的代码导致意外数量的重新渲染.
function App() {
const [isOn, setIsOn] = useState(false)
const [timer, setTimer] = useState(0)
console.log('re-rendered', timer)
useEffect(() => {
let interval
if (isOn) {
interval = setInterval(() => setTimer(timer + 1), 1000)
}
return () => clearInterval(interval)
}, [isOn])
return (
<div>
{timer}
{!isOn && (
<button type="button" onClick={() => setIsOn(true)}>
Start
</button>
)}
{isOn && (
<button type="button" onClick={() => setIsOn(false)}>
Stop
</button>
)}
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
请注意第4行的console.log.我期望以下内容被注销:
重新渲染0
重新渲染0
重新渲染1
第一个日志用于初始渲染.当"isOn"状态通过按钮单击更改时,第二个日志用于重新呈现.第三个日志是setInterval调用setTimer时,它会再次重新渲染.这是我实际得到的:
重新渲染0
重新渲染0
重新渲染1
重新渲染1
我无法弄清楚为什么会有第四个日志.这是一个链接到它的REPL:
https://codesandbox.io/s/kx393n58r7
***只是为了澄清,我知道解决方案是使用setTimer(timer => timer + 1),但我想知道为什么上面的代码会导致第四次渲染.
Rya*_*ell 10
当你调用返回的setter时发生的大部分函数useState
都dispatchAction
在ReactFiberHooks.js内(当前从第1009行开始).
检查状态是否已更改的代码块(如果未更改,则可能会跳过重新呈现)当前包含以下条件:
if (
fiber.expirationTime === NoWork &&
(alternate === null || alternate.expirationTime === NoWork)
) {
Run Code Online (Sandbox Code Playgroud)
我看到这个的假设是这个条件在第二次setTimer
调用后被评估为假.为了验证这一点,我复制了开发CDN React文件并在dispatchAction
函数中添加了一些控制台日志:
function dispatchAction(fiber, queue, action) {
!(numberOfReRenders < RE_RENDER_LIMIT) ? invariant(false, 'Too many re-renders. React limits the number of renders to prevent an infinite loop.') : void 0;
{
!(arguments.length <= 3) ? warning$1(false, "State updates from the useState() and useReducer() Hooks don't support the " + 'second callback argument. To execute a side effect after ' + 'rendering, declare it in the component body with useEffect().') : void 0;
}
console.log("dispatchAction1");
var alternate = fiber.alternate;
if (fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1) {
// This is a render phase update. Stash it in a lazily-created map of
// queue -> linked list of updates. After this render pass, we'll restart
// and apply the stashed updates on top of the work-in-progress hook.
didScheduleRenderPhaseUpdate = true;
var update = {
expirationTime: renderExpirationTime,
action: action,
eagerReducer: null,
eagerState: null,
next: null
};
if (renderPhaseUpdates === null) {
renderPhaseUpdates = new Map();
}
var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
if (firstRenderPhaseUpdate === undefined) {
renderPhaseUpdates.set(queue, update);
} else {
// Append the update to the end of the list.
var lastRenderPhaseUpdate = firstRenderPhaseUpdate;
while (lastRenderPhaseUpdate.next !== null) {
lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
}
lastRenderPhaseUpdate.next = update;
}
} else {
flushPassiveEffects();
console.log("dispatchAction2");
var currentTime = requestCurrentTime();
var _expirationTime = computeExpirationForFiber(currentTime, fiber);
var _update2 = {
expirationTime: _expirationTime,
action: action,
eagerReducer: null,
eagerState: null,
next: null
};
// Append the update to the end of the list.
var _last = queue.last;
if (_last === null) {
// This is the first update. Create a circular list.
_update2.next = _update2;
} else {
var first = _last.next;
if (first !== null) {
// Still circular.
_update2.next = first;
}
_last.next = _update2;
}
queue.last = _update2;
console.log("expiration: " + fiber.expirationTime);
if (alternate) {
console.log("alternate expiration: " + alternate.expirationTime);
}
if (fiber.expirationTime === NoWork && (alternate === null || alternate.expirationTime === NoWork)) {
console.log("dispatchAction3");
// The queue is currently empty, which means we can eagerly compute the
// next state before entering the render phase. If the new state is the
// same as the current state, we may be able to bail out entirely.
var _eagerReducer = queue.eagerReducer;
if (_eagerReducer !== null) {
var prevDispatcher = void 0;
{
prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
}
try {
var currentState = queue.eagerState;
var _eagerState = _eagerReducer(currentState, action);
// Stash the eagerly computed state, and the reducer used to compute
// it, on the update object. If the reducer hasn't changed by the
// time we enter the render phase, then the eager state can be used
// without calling the reducer again.
_update2.eagerReducer = _eagerReducer;
_update2.eagerState = _eagerState;
if (is(_eagerState, currentState)) {
// Fast path. We can bail out without scheduling React to re-render.
// It's still possible that we'll need to rebase this update later,
// if the component re-renders for a different reason and by that
// time the reducer has changed.
return;
}
} catch (error) {
// Suppress the error. It will throw again in the render phase.
} finally {
{
ReactCurrentDispatcher$1.current = prevDispatcher;
}
}
}
}
{
if (shouldWarnForUnbatchedSetState === true) {
warnIfNotCurrentlyBatchingInDev(fiber);
}
}
scheduleWork(fiber, _expirationTime);
}
}
Run Code Online (Sandbox Code Playgroud)
为了清晰起见,这里是控制台输出和一些额外的注释:
re-rendered 0 // initial render
dispatchAction1 // setIsOn
dispatchAction2
expiration: 0
dispatchAction3
re-rendered 0
dispatchAction1 // first call to setTimer
dispatchAction2
expiration: 1073741823
alternate expiration: 0
re-rendered 1
dispatchAction1 // second call to setTimer
dispatchAction2
expiration: 0
alternate expiration: 1073741823
re-rendered 1
dispatchAction1 // third and subsequent calls to setTimer all look like this
dispatchAction2
expiration: 0
alternate expiration: 0
dispatchAction3
Run Code Online (Sandbox Code Playgroud)
NoWork
值为零.您可以看到fiber.expirationTime
after 的第一个日志setTimer
具有非零值.在第二次setTimer
调用的日志中,fiber.expirationTime
已经移动到alternate.expirationTime
仍然阻止状态比较,因此重新呈现将是无条件的.之后,fiber
和alternate
失效时间均为0(NoWork),然后进行状态比较并避免重新渲染.
React Fiber Architecture的这种描述是尝试理解其目的的良好起点expirationTime
.
理解它的源代码中最相关的部分是:
我认为到期时间主要与默认情况下尚未启用的并发模式相关.到期时间表示React将尽早强制提交作品的时间点.在此之前,React可能会选择批量更新.某些更新(例如来自用户交互)具有非常短(高优先级)的到期,并且其他更新(例如,在获取完成后来自异步代码)具有更长(低优先级)到期.setTimer
在setInterval
回调中触发的更新将属于低优先级类别,并且可能被批处理(如果启用了并发模式).由于可能已经批量处理或可能丢弃该工作,因此如果先前的更新具有,则React无条件地排队重新呈现(即使自上次更新后状态未改变)expirationTime
.
你可以在这里看到我的答案,以了解更多关于通过React代码找到你的方法来获得这个dispatchAction
功能.
对于那些想要挖掘自己的人来说,这里有一个CodeSandbox和我修改过的React版本:
react文件是这些文件的修改副本:
https://unpkg.com/react@16/umd/react.development.js
https://unpkg.com/react-dom@16/umd/react-dom.development.js
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3848 次 |
最近记录: |