如何在ReactJs中将变量保存到localStorage

时间:2018-10-22 13:58:03

标签: javascript reactjs local-storage

我想知道如何将变量的值保存到localStorage

我最近学习了如何在JavaScript中进行操作,但是如何在ReactJs中进行操作?

2 个答案:

答案 0 :(得分:1)

您可以使用类似的方式来存储变量并将其加载到本地存储。

export const loadState = (state) => {

    try {
        const serializedState = localStorage.getItem(state);
        if(serializedState === null){
            return undefined;
        }
        return JSON.parse(serializedState);
    } catch (err) {
        return undefined;
    }
};

export const saveState = (state) => {
    try{
        const serializedState = JSON.stringify(state);
        localStorage.setItem('state', serializedState);
    } catch (err){
        return undefined;
    }
}

答案 1 :(得分:0)

您可以使用localStorage及其方法将数据保存到本地存储。请参阅:window.localStorage

https://www.robinwieruch.de/local-storage-react/

是一篇非常有用且内容丰富的文章
// To save the item
localStorage.setItem('email', JSON.stringify(this.state.UserEmail))
  .then(() => console.log('saved email successfully'))
  .catch(err => console.error('something went wrong', err));

// To retrive that item
AsyncStorage.getItem('email')
.then(val => {
  if (val !== null) console.log(val); // You can do whatever you want with the email
})
.catch(err => console.error(err)) // if there was an error fetching data

请注意,如果localStorage中没有任何内容,它将返回“ null”,因此为了处理错误,您需要将它们放入if语句中而不是置于catch中