我有一個將資料保存到本地存盤的邏輯,我找到了一種從本地存盤獲取這些資料的方法,但它僅在我重繪 時才有效,而不是在渲染組件時,我在尋找注入本地存盤資料的方法時遇到了問題將主要組件渲染為默認狀態,我當前的實作是錯誤的我正在使用重新加載函式來實作該目的,如果某些內容發生變化并且用戶回傳頁面,除非用戶重新加載頁面,否則資料更改不會顯示......
// 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;
uj5u.com熱心網友回復:
你總是可以使用useLocalStoragereact-use 中實作的鉤子
const [list, setList, removeList] = useLocalStorage('lst', []);
uj5u.com熱心網友回復:
您可以使用輔助函式進行管道傳輸
const getListFromLS = () => {
//returns null if no items found.
return JSON.parse(localStorage.getItem('lst')) || [];
}
并在您的 setState
const [list, setList] = useState(getListFromLS());
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/396295.html
標籤:javascript 反应
