簡體   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