簡體   English   中英

如何在 React 的本地存儲中保存 darkMode?

[英]How to save darkMode in local storage in React?

我想在本地存儲中保存用戶選擇的主題 - 淺色或深色,以便在頁面刷新時主題仍然符合用戶的選擇。 我嘗試為此使用 useEffect 掛鈎,但我可能做錯了什么。 我已經包含了下面的代碼:

function App() {
// Theme
    const [theme, setTheme] = useState('light');
    const checkTheme = () => theme === 'light' ? setTheme('dark') : setTheme('light') ;

// Amount of Portions
const [amountOfPortions , setAmountOfPortions] = useState(1);

const updateAmountOfPortions = (dataFromChild) => {
    setAmountOfPortions(dataFromChild);
};

return (
    <div className={`app wrapper app__bgc--${theme}`}>
        <Switch onChange={checkTheme} color="primary"/>
        <MainCard update={updateAmountOfPortions}/>
        <Recipe value={amountOfPortions}/>
    </div>
    
)};

您只是設置 state,一旦組件刷新,它就會丟失

您需要使用 localStorage api 編寫一個 function。類似於:

const setThemeInStorage = (theme) => {
   localStorage.setItem('theme', theme)
}

然后像這樣稱呼它

setThemeInStorage('light')

並像這樣檢索它:

const getThemeInStorage = () => {
   localStorage.getItem('theme') // returns 'light' in this case
}

如果你想立即運行這段代碼

const theme = getThemeInStorage()那么theme就是localStorage的值

這個怎么樣?

function persistItem(key: string, value: string) {
    localStorage.setItem(key, value)
    return value
}

function usePersistState(key: string, initialValue?: string) {
    const [state, setState] = useState(
        () => localStorage.getItem(key) || persistItem(key, initialValue)
    )
    const setStateAndPersist = useCallback(
        (newState: string) => {
            setState(newState)
            return persistItem(key, newState)
        },
        [key, setState]
    )
    return [state, setStateAndPersist]
}

在您的組件中,只需const [theme, setTheme] = usePersistState("theme", "light") 如果在localStorage中找不到任何內容,這將默認為“light”。

最簡單的方法是使用像useLocalStorage這樣的自定義鈎子。 如果你不想使用鈎子,他們仍然有實現localStorage寫入/讀取部分的代碼,並附有注釋解釋他們是如何做到的,這樣你就可以用不同的方式來做到這一點(雖然我不明白為什么你將)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM