[英]Using ReactJS to store array items across multiple pages
我在 React 中構建了一個導航組件,其構造函數如下所示:
constructor(props) {
super(props);
var BCList_store = localStorage.getItem('SelectedOption')
const BCList = [];
BCList.push({
name: document.title
});
this.state = {
BCList
};
this.setState({ BCList });
localStorage.setItem('SelectedOption', JSON.stringify(BCList));
}
這個想法是每次用戶加載頁面時,都會使用數組調用 localStorage,將頁面標題推送到數組,更新狀態,然后 localStorage 使用新值保存數組。
但是,當加載新頁面時,數組仍然會被清除,並且只出現一個數組項(當前頁面標題)。 我是否錯誤地使用了 localStorage 還是有其他方法可以做到這一點? 謝謝
你需要在這里了解兩件事
當您在本地存儲中設置/獲取應該是字符串的項目時。 因此,當您將數組設置為轉換為字符串的本地存儲時,您可以通過打印 localStorage.getItem('SelectedOption') 來檢查它。
構造函數(道具){ 超級(道具);
let newArray=[], previousArray = localStorage.getItem('SelectedOption') ; if(previousArray){ newArray = JSON.parse(previousArray); } const BCList = []; BCList.push({ name: document.title }); this.state = { BCList }; // push the current item newArray.push({ name: document.title }); this.setState({ BCList }); localStorage.setItem('SelectedOption', JSON.stringify(newArray));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.