之前我们是把异步ajax 请求直接放在了组件 app.js 中了,当逻辑十分复杂时,我们最好是将这些异步请求放在一个地方进行统一的管理。
下面就是我们之前的代码,看看。
import React, { Component } from 'react';
import './mockdata.js';
import axios from 'axios';
import "antd/dist/antd.css";
import { List, Input, Button } from 'antd';
import store from './store/index.js';
class App extends Component {
constructor(props) {
super(props);
this.state = store.getState();
this.handleStoreChange = this.handleStoreChange.bind(this);
store.subscribe(this.handleStoreChange);
}
componentDidMount() {
axios.get("api/list.json",{dataType: 'json'}).then( res => {
console.log(res.data);
const action = {
type: "init_List",
value: res.data.names
};
store.dispatch(action);
})
}
render() {
return (
<div style = {{marginTop: '10px',marginLeft: '10px'}}>
<div style={{width: '300px'}}>
<Input
style={{width: '235px',marginRight: '5px'}}
value={this.state.inputValue}
placeholder="Basic usage"
onChange={this.handleInputChange}
/>
<Button
onClick = {this.handleButtonClick}
>
Add
</Button>
</div>
<List
style={{width: '300px'}}
header={<div>Header</div>}
footer={<div>Footer</div>}
bordered
dataSource={this.state.names}
renderItem={(item, index) => (<List.Item onClick={this.handleItemCLick.bind(this.index)}>{item}</List.Item>)}
/>
</div>
);
}
handleInputChange(e) {
const action = {
type: 'change_input_value',
value: e.target.value
}
store.dispatch(action);
}
handleButtonClick() {
const action = {
type: 'add_input_value'
}
store.dispatch(action);
}
handleItemCLick(index) {
const action = {
type: 'delete_Item',
index
}
store.dispatch(action);
}
handleStoreChange() {
this.setState(store.getState());
}
}
export default App;
非常不清晰。我们可以把这些异步请求放到其它地方。Redux-thunk 中间件可以使我们把异步请求或者复杂的逻辑,放到action 中去处理.
这是rudux-thunk 在github 上的地址 https://github.com/reduxjs/redux-thunk
那么,我们先来安装一下 redux-thunk
yarn add redux-thunk
然后启动项目
好啦,首先,安装官网说的。在创建store的时候要使用这个中间件。还要引入redux-thunk。再在store 中使用这个中间件,如下。
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import reducer from './reducer';
const store = createStore(
reducer,
applyMiddleware(thunk)
);
export default store;
然后可以重启服务了。
下面我们把异步请求抽出来,在src 下新建一个文件 actionCreators.js 。然后呢,我们把异步请求代码放进来,如下。
import axios from 'axios';
export const getTodoItem = () => {
return () => {
axios.get("api/list.json",{dataType: 'json'}).then( res => {
console.log(res.data);
// const action = {
// type: "init_List",
// value: res.data.names
// };
// store.dispatch(action);
})
}
}
然后,我们再在 app.js 中的componentDidMount 生命周期函数 修改为这样.dispacth中的函数会被自动执行。
componentDidMount() {
const getData = getTodoItem();
store.dispatch(getData);
}
好啦,我们再更改一下actionCreators.js 文件,如下。
import axios from 'axios';
export const getTodoItem = () => {
return (dispatch) => {
axios.get("api/list.json",{dataType: 'json'}).then( res => {
console.log(res.data);
const action = {
type: "init_List",
value: res.data.names
};
dispatch(action);
})
}
}