簡體   English   中英

使用useEffect渲染主要組件時,如何從本地存儲中設置反應state?

[英]How to set react state from local storage when rendering main component, using useEffect?

我有一個將數據保存到本地存儲的邏輯,我找到了一種從本地存儲中獲取這些數據的方法,但它僅在我刷新時才有效,而不是在我渲染組件時,我在尋找注入本地存儲數據的方法時遇到問題將主要組件呈現為默認 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;

你總是可以使用 react-use 中實現的useLocalStorage鈎子

 const [list, setList, removeList] = useLocalStorage('lst', []);

你可以用一個助手 pipe function

const getListFromLS = () => {
    //returns null if no items found.
    return JSON.parse(localStorage.getItem('lst')) || [];
}

在你的 setState

const [list, setList] = useState(getListFromLS());

暫無
暫無

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

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