gpt4 book ai didi

reactjs - 如果随后释放并设置状态,React hook useRender 会调用两次

转载 作者:行者123 更新时间:2023-12-03 14:22:06 25 4
gpt4 key购买 nike

我不确定这是否是预期的行为,但是如果您在使用 useReducer Hook 时退出调度 ( 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。 但是,如果我要更改 reducer ,使其不会像下面这样,它们都会增加增加 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

包装时才会发生

有谁知道这是什么原因吗???

最佳答案

根据doc of StrictMode ,react 故意使用相同的操作调用 reducer 函数两次,以便暴露未被注意到的潜在有害副作用,这正是您的情况所发生的情况。

Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions: […] Functions passed to useState, useMemo, or useReducer

关于reactjs - 如果随后释放并设置状态,React hook useRender 会调用两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61583638/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com