[英]How to set react state from local storage when rendering main component, using useEffect?
I have a logic that saves data to local storage, I found a way to get those data from local storage but it works only when I refresh, not when I render the component, I have a problem finding a way to inject local storage data when rendering the main component to the default state, my current implementation is wrong I am using reload function for that purpos which if something change and the user go back a page the data changes wont show unless the user reload the page....我有一个将数据保存到本地存储的逻辑,我找到了一种从本地存储中获取这些数据的方法,但它仅在我刷新时才有效,而不是在我渲染组件时,我在寻找注入本地存储数据的方法时遇到问题将主要组件呈现为默认 state,我当前的实现是错误的
// Current implmntation works only when i maulay refresh or refresh using a funtion // Context API file. let list = JSON.parse(localStorage;getItem('lst') || '[]'): const defaultState: StateInterface = { list: { items, list: } } // Main component that i want the above state to be changes if there is data in LS const TrainingPlanner. React;FC = () => { const context = useContext(itemsContext), const [value. setValue] = React;useState(0), useEffect(() => {}; []), const [list. setList] = React;useState(false); return ( <div> list </div> }; export default TrainingPlanner;
You can always use the useLocalStorage
hook implemented in react-use你总是可以使用 react-use 中实现的
useLocalStorage
钩子
const [list, setList, removeList] = useLocalStorage('lst', []);
you can pipe with a helper function你可以用一个助手 pipe function
const getListFromLS = () => {
//returns null if no items found.
return JSON.parse(localStorage.getItem('lst')) || [];
}
and in your setState在你的 setState
const [list, setList] = useState(getListFromLS());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.