reactjs - 组件挂载时如何获取本地存储值?
问题描述
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
}
解决方案
// 在 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/ 我希望这会有所帮助。
推荐阅读
- php - Laravel 和 Vuejs 的跨域资源共享 (CORS)
- macos - 在网站上下载阻止检查元素的视频
- jenkins-pipeline - 使用 jenkins 管道的 Liquibase 实现
- java - 如何创建包含所有特定对象总和的地图?
- istio - 如何防止 Istio sidecar 在我的服务正常终止之前关闭?
- flutter - 如果在屏幕上向下滚动,颤动如何更新 Listview.builder
- multithreading - 是否可以将 COM 对象从后台 STA 线程返回到主 STA 线程并在那里使用它?
- mysql - 当我将网站上传到生产环境时,如何修复错误 500
- typescript - Serverless ExpressJS Typescript 应用程序中的 VSCode 断点不起作用
- css - 如何在容器内灵活