繁体   English   中英

useState 没有更新我的应用程序的所有组件

[英]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>
  );
}
  • 或者,改用上下文 API 它需要更多设置,但是当您想在父级中创建某些东西并允许每个后代使用它时,无论它在组件树中的什么位置,这是一个很好的方法,而无需手动将值作为道具传递到任何地方。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM