更新本地和父状态导致未安装的组件错误
Updating local and parent state causes unmounted component error
I have a table with buttons。我想跟踪单击每个按钮的次数以及单击任何按钮的总次数。我只能让一个或另一个工作。
我试图通过将“全局”状态挂钩传递到用于跟踪总点击次数的 table 的每一行来实现这一点。我还有一个“本地”状态挂钩,它是构成 table 中一行的每个组件的一部分,用于跟踪单个点击。我将“全局”状态从父行传递到子行作为一对回调(一个用于 getter,一个用于 setter)。
错误信息:
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
in ButtonCell (created by clickableButtonCell)
in clickableButtonCell (created by Table)
有问题的代码:
export default function ButtonCell({
totalButtonClicks,
setTotalButtonClicks
}) {
// Having this local state variable causes the unmounted component error.
// Removing this state and its references will cause the error to go away.
// Or, removing the state variable passed into this component will cause
// the error to go away and the individualClicks state will work as intended.
const [individualClicks, setIndividualClicks] = useState(0);
const onClick = async () => {
await axios.get("www.github.com").then(() => {
setTotalButtonClicks(totalButtonClicks + 1);
setIndividualClicks(individualClicks + 1);
return null;
});
};
return (
<button type="button" onClick={onClick}>
Click Me! {individualClicks}
</button>
);
}
代码沙箱: https://codesandbox.io/s/cranky-sun-wflot?file=/src/ButtonCell.js
编辑:https://codesandbox.io/s/hopeful-wing-7cwio?file=/src/ButtonCell.js
MyTable.js 中的 useMemo 因道具更改(由设置状态引起)而导致重新渲染。
I have a table with buttons。我想跟踪单击每个按钮的次数以及单击任何按钮的总次数。我只能让一个或另一个工作。
我试图通过将“全局”状态挂钩传递到用于跟踪总点击次数的 table 的每一行来实现这一点。我还有一个“本地”状态挂钩,它是构成 table 中一行的每个组件的一部分,用于跟踪单个点击。我将“全局”状态从父行传递到子行作为一对回调(一个用于 getter,一个用于 setter)。
错误信息:
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
in ButtonCell (created by clickableButtonCell)
in clickableButtonCell (created by Table)
有问题的代码:
export default function ButtonCell({
totalButtonClicks,
setTotalButtonClicks
}) {
// Having this local state variable causes the unmounted component error.
// Removing this state and its references will cause the error to go away.
// Or, removing the state variable passed into this component will cause
// the error to go away and the individualClicks state will work as intended.
const [individualClicks, setIndividualClicks] = useState(0);
const onClick = async () => {
await axios.get("www.github.com").then(() => {
setTotalButtonClicks(totalButtonClicks + 1);
setIndividualClicks(individualClicks + 1);
return null;
});
};
return (
<button type="button" onClick={onClick}>
Click Me! {individualClicks}
</button>
);
}
代码沙箱: https://codesandbox.io/s/cranky-sun-wflot?file=/src/ButtonCell.js
编辑:https://codesandbox.io/s/hopeful-wing-7cwio?file=/src/ButtonCell.js MyTable.js 中的 useMemo 因道具更改(由设置状态引起)而导致重新渲染。