1:中间件流程图
2:Redux-thunk作用:
简单说:当组件中有复杂的异步请求时,为了减少组件的复杂程度
把异步请求使用此中间件放在actionCreator.js中
3:使用之前
使用之前是在组件内进行数据请求
store/index.js
//store.js
import {createStore,applyMiddleware} from 'redux';
import reducer from './reducer';
import thunk from 'redux-thunk';
//1-store是唯一的
//2-只有store才能改变自己的内容(state)
//3-reducer必须是纯函数
const store = createStore(
reducer,
);
export default store;
TodoList.js
//TododList.js
//视图渲染之后使用axios进行ajax请求,进行初始化
componentDidMount(){
axios.get('https://api.github.com/users')//上面已经引入地址
.then((res)=>{
// console.log(res);//得要所有结果
const data=res.data;//具体看数据
// console.log(data)
const action=initListAction(data);
store.dispatch(action);
})
}
store/actionCreator.js
//actionCreator.js
export const initListAction=(data)=>({
type:INIT_LIST_ACTION,
data,
});
4:使用
使用之后是在actionCreator.js中进行网络请求
4.1:安装:
npm install --save redux-thunk
4.2:使用:在store/index.js中引用(已经安装了react官方脚手架)
store/index.js
import {createStore,applyMiddleware} from 'redux';
import reducer from './reducer';
import thunk from 'redux-thunk';
//1-store是唯一的
//2-只有store才能改变自己的内容(state)
//3-reducer必须是纯函数
const store = createStore(
reducer,
applyMiddleware(thunk),//这个方法表示:使用thunk这个中间件
);
export default store;
TodoList.js
//TododList.js
//视图渲染之后使用axios进行ajax请求,进行初始化
componentDidMount() {
const action = getTodoList();//此时action返回的不再是一个对象,而是一个函数,
store.dispatch(action);//此时action是个函数,这个函数执行完了之后,才最后转发给store,store自动转发给reducer
}
store/actionCreator.js
//actionCreator.js
export const initListAction=(data)=>({
type:INIT_LIST_ACTION,
data,
});
//使用redux-thunk中间件之后允许返回一个函数
export const getTodoList=()=>{
return (dispatch)=>{
axios.get('https://api.github.com/users')//上面已经引入地址
.then((res)=>{
const data=res.data;
const action=initListAction(data);
dispatch(action);//转发给调用此方法的常量
})
}
};