我想在本地存储中保存用户选择的主题-光还是暗,这样当页面刷新时,主题仍然符合用户的选择。我试着用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>
)};发布于 2022-03-28 16:24:18
您只是在设置一旦组件刷新就会丢失的状态。
您需要使用localStorage api编写一个函数。类似于:
const setThemeInStorage = (theme) => {
localStorage.setItem('theme', theme)
}那就叫它吧
setThemeInStorage('light')并以如下方式检索:
const getThemeInStorage = () => {
localStorage.getItem('theme') // returns 'light' in this case
}如果您想立即运行此代码,请执行以下操作
const theme = getThemeInStorage()然后theme是localStorage的值
发布于 2022-03-29 14:52:01
这个怎么样?
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“。
发布于 2022-03-28 16:25:06
最简单的方法是使用像useLocalStorage这样的自定义钩子。如果您不想使用钩子,那么它们仍然有实现localStorage编写/读取部分的代码,并附带注释说明它们是如何实现的,这样您就可以以不同的方式完成它(尽管我不知道为什么要这样做)。
https://stackoverflow.com/questions/71650492
复制相似问题