嘿嘿。使用 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 組件沒有重新渲染嗎?
uj5u.com熱心網友回復:
它們是完全獨立的狀態。這個:
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。它需要更多設定,但是當您想在父級中創建某些東西并允許每個后代使用它時,無論它在組件樹中的什么位置,這是一個很好的方法,而無需手動將值作為道具傳遞到任何地方。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/495293.html
標籤:javascript 反应 使用状态
