首页 > 解决方案 > 组件挂载时如何获取本地存储值?

问题描述

localStorage加载页面时我在获取价值时遇到问题

如果我刷新它正在工作的页面。

localStorage页面加载时如何获取值。

我有两个文件一个是 utils.js 在这个文件中我已经声明了一个对象

export const user = {
      id: window.localStorage.userId
    };

另一个是这个页面中的 userDetails.js 我有一个价值

import {user} from './utils';

componentDidMount=() => {
   console.log(user.id);//for the first time its getting null .when i refresh the page value is updated
}

标签: reactjs

解决方案


// 在 React 中使用 state 和 props 概念进行数据流
// Util.js

import React, Component from 'react'; 
class Utils extends Component{
        state = {
            user: {
                 id: window.localStorage.userId
            }
        } 
}  
export default Utils;


//UserDetails.js
import React, Component from 'react';
import Utils from './Utils';
class UserDetails extends Component{
    componentDidMount=() => {
        console.log(this.props.user.id);//One time
    }
    componentWillReceiveProps(newProps){
        if(this.props.user !== newProps.user)
            console.log(newProps.user); // Each time props changes
    }
}

此外,redux 可用于全局状态管理 https://redux.js.org/ 我希望这会有所帮助。


推荐阅读