简体   繁体   English

使用useEffect渲染主要组件时,如何从本地存储中设置反应state?

[英]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.

相关问题 反应:尝试使用本地 JSON 数据通过 useEffect 设置 state - React: Trying to set state via useEffect using local JSON data 如何在 React 的 useEffect 中设置状态? - How to set the state in useEffect in React? 反应:如何在 State 使用`useEffect`更改时显示微调器和组件(同时) - React: How to show Spinner & Component (at the same time) when State Changes using `useEffect` 如何在反应时从本地存储中检索状态 - How to retrieve state from local storage on react 在 React.js 中安装组件之前,如何从本地存储中加载 state? - How to load state from local storage before mounting the component in React.js? React Hooks:在 useEffect 中使用 useState 不会在第一次渲染后立即设置状态 - React Hooks: using useState inside useEffect doesn't set the state immediately after first rendering 将React.component状态与本地存储同步 - Sync React.component state with local storage 当 chrome.storage.local 中的数据发生变化时,使用 Effect 更新 state - useEffect to to update a state when data in chrome.storage.local changes 使用 useEffect 挂钩获取数据时,React 组件不会在 URL 参数更改上重新渲染 - React component not re-rendering on URL parameter change when using useEffect hook to fetch data 更改 state 时如何重新渲染反应 class 组件 - How to re-rendering react class component when state is changed
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM