react 如何处理页面加载时无法将获取缓存信息存入全局变量中
最近在做一个权限功能时,发现在读取用户公司ID进行列表查询 时,无法钭读取到缓存中的数据存入页面全局变量中进行加载查询
将问题代码整理出来
将信息存入缓存:
let menuList = Helper.getUserInfo();localStorage.setItem('_io_iframe_admin_menu_list_key_', JSON.stringify(menuList));
读取缓存,加载前存入param变量中给请求作参数用
import React from 'react';import { Form,Input,Button,Popconfirm,Select,DatePicker } from 'antd';
let prolist = LocalService.getUserInfo() && JSON.parse(LocalService.getUserInfo()) || [] ;
let order = React.createClass({
mixins: [LoadingMixin,NotificationMixin,RequestMixin],
getInitialState(){
return {
data: [],
param:{},
}
},
componentWillMount(){
if(prolist){
var param ={}
param.companyid = prolist.cid
this.setState({param: param || []});
}
this.getlists()
},
getlists(){
this.get({
url: "Api/lists/****",
param: {
companyid:this.state.param && this.state.param.companyid || ''
},
noLoading: true
}).then(result=> {
this.setState({data: result.result || []});
});
},
...
});
此时缓存中能取到数据,但get请求中参数却为空
原因在于get异步请求时,变量存储动作还未完成,
可将存储动作在getInitialState()生命周期内完成,则在componentWillMount()生命周期中调取get请求就能正常获取变量参数了
1 import React from 'react';2 import { Form,Input,Button,Popconfirm,Select,DatePicker } from 'antd';
3
4 let prolist = LocalService.getUserInfo() && JSON.parse(LocalService.getUserInfo()) || [] ;
5 let paraming ={}
6 paraming.companyid = prolist.cid
7
8 let order = React.createClass({
9 mixins: [LoadingMixin,NotificationMixin,RequestMixin],
10 getInitialState(){
11 return {
12 data: [],
13 param:paraming && paraming || {},
14 }
15 },
16 componentWillMount(){
17 this.getlists()
18 },
19 getlists(){
20 this.get({
21 url: "Api/lists/****",
22 param: {
23 companyid:this.state.param && this.state.param.companyid || ''
24 },
25 noLoading: true
26 }).then(result=> {
27 this.setState({data: result.result || []});
28 });
29 },
30
31 ...
32
33 });
以上是 react 如何处理页面加载时无法将获取缓存信息存入全局变量中 的全部内容, 来源链接: utcz.com/z/381493.html