我不确定这是否是预期的行为,但是如果您在使用 useReducer 时退出调度( https://reactjs.org/docs/hooks-reference.html#bailing-out-of-a-dispatch )钩子,如果后面跟着渲染,动作会发生两次。让我解释:
// bailing out to prevent re-rendering
const testReducer = (state, action) => {
switch (action.type) {
case "ADD":
state.test += 1
return state;
}
};
const myComponent = () => {
let [totalClicks, setClicks] = useState(0);
const [state, setState] = useReducer(testReducer, {
test: 0,
});
const clickHandler = () => {
setState({type: 'ADD'});
setClicks((totalClicks += 1));
};
return (
<div>
<button onClick={clickHandler}>+</button>
<p>{totalClicks}</p>
<p>test count: {state.test}</p>
</div>
);
}
当您单击按钮时,state.test 增加 2,而 totalClicks 增加 1。但是,如果我要更改减速器,使其不会像下面那样保释,它们都会增加 1。
// non-bailing reducer
const testReducer = (state, action) => {
switch (action.type) {
case "ADD":
return {
test: state.test + 1,
};
}
};
为什么是这样?这是预期的行为还是错误?沙盒示例:https ://codesandbox.io/s/sad-robinson-dds63?file=/src/App.js
更新: 在做了一些调试之后,看起来这种行为只在用React.StrictMode包装时发生
有谁知道这是什么原因???