我有一个在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还是应该采用另一种方法? 谢谢
答案 0 :(得分:1)
您需要在这里了解两件事
当您将项目设置为本地存储或从本地存储中获取时,应该为字符串。 因此,当您将数组设置为本地存储并将其转换为字符串时,可以通过打印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));
}