使用ReactJS在多个页面上存储数组项

时间:2018-08-20 03:23:25

标签: javascript reactjs

我有一个在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还是应该采用另一种方法? 谢谢

1 个答案:

答案 0 :(得分:1)

您需要在这里了解两件事

  1. 当您将项目设置为本地存储或从本地存储中获取时,应该为字符串。 因此,当您将数组设置为本地存储并将其转换为字符串时,可以通过打印localStorage.getItem('SelectedOption')进行检查。

    1. 您正在用新值覆盖键,因此需要在新值后附加上一个值。

    构造函数(道具){     超级(道具);

    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));          
    

    }