react中使用redux简易案例讲解
为什么我想要使用redux?
前段时间初步上手了react,最近在使用react的过程中发现对于组件之间通信的需求比较迫切,尤其是在axios异步请求后端数据的时候,这样的需求是特别强烈的!举个例子:
// 厂家报告到货
class ReportArrivalGoods extends React.Component{
constructor(props){
super(props);
this.state = {
columns:tableHead.ReportArrivalGoods,//这里是初始化的表头,内容较多,不显示出来了
data: []
};
}
componentDidMount(){
axios(
{
method: 'get',
url: 'http://172.89.1.79/LogisticsSporadicBoardBackEnd/index.asmx/ReportArrivalGoods'
})
.then(
res => {
this.setState(
data:NewState
);
}
)
.catch(
error => {
console.log(error);
}
);
}
render(){
return(
<Table
style={{width: '100%'}}
columns={this.state.columns}
data={this.state.data}
border={true}
maxHeight={tableMaxHeight}
/>
);
}
}
我们聚焦于下面的componentDidMount()函数
componentDidMount(){
axios(
{
method: 'get',
url: 'http://172.89.1.79/LogisticsSporadicBoardBackEnd/index.asmx/ReportArrivalGoods'
})
.then(
res => {
this.setState(
data:NewState
);
}
)
.catch(
error => {
console.log(error);
}
);
}
这是大家都很熟悉的react生命周期钩子函数,我做了这样一件事:页面渲染完向后台请求数据并显示到页面上。但是用过axios的都知道,他跟ajax一样,都是异步的,也就说,你发处请求后就会立即执行后面的代码了,等你请求结果回来了才会执行then()和catch()。一开始我简单粗暴的直接把整个函数体写进了钩子中,实现是没问题了,可是要使用钩子函数请求不同数据的组件有5个,要是每个组件都写这么一长串代码,一方面不好看,另一方面重复代码太多了。于是我想到了把这段函数体封装起来,于是就有下面的代码
//webservice数据请求函数function AxiosGet(desinationURL){ axios( { method: 'get', url: desinationURL }) .then( res => { ); } ) .catch( error => { console.log(error); } ); }