最近在做一个权限功能时,发现在读取用户公司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请求就能正常获取变量参数了
import React from 'react';
import { Form,Input,Button,Popconfirm,Select,DatePicker } from 'antd'; let prolist = LocalService.getUserInfo() && JSON.parse(LocalService.getUserInfo()) || [] ;
let paraming ={}
paraming.companyid = prolist.cid let order = React.createClass({
mixins: [LoadingMixin,NotificationMixin,RequestMixin],
getInitialState(){
return {
data: [],
param:paraming && paraming || {},
}
},
componentWillMount(){
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 || []});
});
}, ... });