我正在阅读一篇名为“A Complete Guide to useEffect ” 并尝试实现和来自“Why useReducer Is the Cheat Mode of Hooks 的示例”部分。
在该示例中,有一个 Counter
组件在 useReducer
钩子(Hook)的帮助下定义状态(只是一个数字)。 Reducer 只处理一个 Action ——'tick'
,在该 Action 上它会根据 step
属性的值递增状态。 'tick'
操作在 useEffect
钩子(Hook)中设置的间隔函数中每秒调度一次。
以下是该示例的代码,稍作修改:
function Counter({ step }) {
const [count, dispatch] = React.useReducer(reducer, 0);
function reducer(state, action) {
if (action.type === "tick") {
console.log(`Reducer: state=${state} and step=${step}`);
return state + step;
} else {
throw new Error(`Unknown action type: ${action.type}`);
}
}
React.useEffect(() => {
console.log("Create interval");
const id = setInterval(() => {
console.log("Dispatch");
dispatch({ type: "tick" });
}, 1000);
return () => {
console.log("Clear interval");
clearInterval(id);
};
}, [dispatch]);
return <h1>{count}</h1>;
}
function App() {
const [step, setStep] = React.useState(0);
return (
<>
<Counter step={step} />
<input
type="number"
value={step}
onChange={(e) => setStep(Number(e.target.value))}
/>
</>
);
}
我发现该示例适用于 react@16.8.0-alpha.0
而不适用于 react@16.8.0
及更高版本。当我运行代码时,步长和计数器的初始值为 0
。如果我等待 3 秒而不做任何更改,然后增加步骤,我将得到以下输出:
Create interval
Dispatch
Reducer: state=0 and step=0
Dispatch
Reducer: state=0 and step=0
Dispatch
Reducer: state=0 and step=0
Reducer: state=0 and step=1
Reducer: state=1 and step=1
Reducer: state=2 and step=1
Dispatch
Reducer: state=3 and step=1
Reducer: state=3 and step=1
Dispatch
Reducer: state=4 and step=1
Dispatch
Reducer: state=5 and step=1
正如您在日志中看到的,reducer 的执行次数超过了 “tick”
操作的调度次数。
我已经设法通过从 step
prop 创建一个 ref 并使用 useCallback
钩子(Hook)记住 reducer 而没有任何依赖性,使其按预期工作。
const stepRef = React.useRef(step);
React.useEffect(() => {
stepRef.current = step;
}, [step]);
const reducer = useCallback((state, action) => {
if (action.type === "tick") {
console.log(`Reducer: state=${state} and step=${stepRef.current}`);
return state + stepRef.current;
} else {
throw new Error(`Unknown action type: ${action.type}`);
}
}, []);
您可以在这里尝试示例:
- Buggy one from the article (如果您将 React 版本更改为
react@16.8.0-alpha.0
,它将按预期工作); - Fixed one (适用于两个版本)。
但问题仍然存在。
useReducer
Hook 的那些行为(react@16.8.0-alpha.0
或react@16.8.0
)是什么错误的例子在现在的 React 中被认为是正确的?- 这是一个错误吗?
- 如果这不是错误,那么为什么它会以这种方式工作并且 reducer 的触发次数超过了需要?
最后一个问题的答案应该与正在重新创建 reducer 的事实有某种关系。无论是在每次渲染时还是仅在 step
属性发生变化时,都没有关系,因为使用 useCallback
钩子(Hook)和传递 [step]
来记住 reducer因为依赖数组不能解决问题。有人对此有任何想法吗?
谢谢!
最佳答案
useReducer
需要记住 reducer
才能说明组件是否需要重新渲染(需要它来计算状态并将其与之前的状态进行比较)。但是它可以访问的 reducer 可能已经过时,因为您可以“交换” reducer 。因此,在 reducer 状态与前一个相同的情况下,React 不会将结果丢弃并收工,而是将结果以及用于计算它的 reducer 存储起来,直到下一次重新渲染和然后检查 reducer 是否仍然相同。如果不是,则使用新的 reducer 再次计算状态。
你的例子是一个边缘案例。它不应该那样工作,但 React 不知道什么时候它应该丢弃陈旧的 reducer 状态更新——它总是等到下一次重新渲染来比较 reducer 并计算将在重新渲染中使用的最终状态。
这是一个描述它的简化示例:
最初 step
是 0
。 dispatch
运行了 3 次。结果是
0 + 0 + 0 = 0
并且显示正确。然后,当您单击该按钮时,step
更改为 1
但 dispatch
甚至一次都不会触发。尽管如此,现在的结果是 3
,因为之前的所有操作都使用新创建的 reducer 重新运行。
function App() {
console.log("rendering");
const [step, setStep] = React.useState(0);
const [count, dispatch] = React.useReducer(reducer, 0);
function reducer(state, action) {
if (action.type === "tick") {
console.log(`Reducer: state=${state} and step=${step}`);
return state + step;
}
}
React.useEffect(() => {
for(let i = 0; i < 3; i++) {
console.log("Dispatch");
dispatch({ type: "tick" });
}
}, []);
return (
<div>
<span>{count} </span>
<button
onClick={(e) => setStep(step + 1)}
>step +1</button>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.development.js"></script>
<div id="root"></div>
解决方案是使 reducer 纯净(从一开始就应该如此)并在 action.payload
中传递所有必需的数据(如果需要,ref
ing things ).
function reducer(state, action) {
if (action.type === "tick") {
const { step } = action.payload;
console.log(`Reducer: state=${state} and step=${step}`);
return state + step;
}
}
function Counter({ step }) {
const [count, dispatch] = React.useReducer(reducer, 0);
const stepRef = React.useRef();
stepRef.current = step;
React.useEffect(() => {
console.log("Create interval");
const id = setInterval(() => {
console.log("Dispatch");
dispatch({ type: "tick", payload: { step: stepRef.current }});
}, 1000);
return () => {
console.log("Clear interval");
clearInterval(id);
};
}, [dispatch]);
return <span>{count} </span>;
}
function App() {
const [step, setStep] = React.useState(0);
return (
<div>
<Counter step={step} />
<input
type="number"
value={step}
onChange={(e) => setStep(Number(e.target.value))}
/>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.development.js"></script>
<div id="root"></div>
关于javascript - 当 reducer 函数依赖于组件 prop 时,传递给 useReducer 钩子(Hook)的 Reducer 函数会针对一次调度调用执行多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63632469/