【发布时间】:2020-08-18 08:56:02
【问题描述】:
我不确定这是否是预期的行为,但是如果您在使用 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
包装时才会发生有谁知道这是什么原因???
【问题讨论】:
-
您能否为此创建一个可重现的示例。我创建了一个,没有发现任何问题。 codesandbox.io/s/hooks-state-non-pure-update-d83uo
-
附加。看了你的之后,我不明白我在做什么的区别以及为什么我的行为如此。 codesandbox.io/s/sad-robinson-dds63?file=/src/App.js
标签: reactjs react-hooks use-state use-reducer react-lifecycle-hooks