[英]useState not updating all components of my app
嘿嘿。 使用 react ,我遇到了一个令人费解的问题。
import { useState } from "react";
function useTheme() {
const [themeName, setThemeName] = useState("dark");
return [themeName, setThemeName];
}
function Other() {
const [themeName, setThemeName] = useTheme();
return <div>{themeName}</div>;
}
function ThemeSwitcher() {
const [themeName, setThemeName] = useTheme();
return (
<>
<button
onClick={() => {
themeName == "dark" ? setThemeName("light") : setThemeName("dark");
}}
>
{"BUTTON"}
</button>
{themeName}
</>
);
}
function App() {
const [themeName, setPalette] = useTheme();
return (
<div>
<ThemeSwitcher />
<Other />
<div>{themeName}</div>
</div>
);
}
export default App;
这是我的问题的一个非常基本的版本,我已经删除了我能想到的所有内容,但它仍然存在。 我有一个带有名为 useTheme 的钩子的应用程序,它提供了一个更改状态变量“themeName”名称的函数。
我有一个按钮组件 ThemeSwitcher,点击它,可以在“暗”和“亮”之间切换主题的名称。
单击按钮时,themeName 状态变量会更新(我肯定知道,因为 ThemeSwitcher 中的 {themeName} 片段会正确更新)。 但是,App 中的 {themeName} 和 Other 中的 {themeName} 实际上并没有更新。 我看不到这里的区别,我目前对为什么一个人会更新而不是其他人感到困惑。
知道为什么尽管状态变量发生变化,但 App 组件没有重新渲染吗?
它们是完全独立的状态。 这个:
function useTheme() {
const [themeName, setThemeName] = useState("dark");
return [themeName, setThemeName];
}
实际上与使用useState
本身没有什么不同。 所以你的问题类似于问为什么,在这里:
function Other() {
const [themeName, setThemeName] = useState();
return <div>{themeName}</div>;
}
function ThemeSwitcher() {
const [themeName, setThemeName] = useState();
// ...
这两个themeNames
名称不同步 - 这是因为它们彼此没有联系。
要解决此问题,通常可以使用两种方法:
function App() {
const [themeName, setThemeName] = useTheme();
return (
<div>
<ThemeSwitcher {...{ themeName, setThemeName }} />
<Other {...{ themeName, setThemeName }} />
<div>{themeName}</div>
</div>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.