1、Redux-thunk中间件 使用方法
第一步 安装redux-thunk中间件
npm install redux-thunk
第二步 在store中引入thunk组件
import {
createStore,applyMiddleware } from 'redux';
import Reducer from './Reducer';
import thunk from 'redux-thunk';
const store = createStore(Reducer,applyMiddleware(thunk));
export default store;
第三步 封装异步请求方法
import React, {
Component } from 'react'
import Store from './Store'
import axios from 'axios'
export class TodoList extends Component {
constructor(props){
super(props);
this.state = Store.getState();
this.handleStoreChange = this.handleStoreChange.bind(this);
Store.subscribe(this.handleStoreChange);
}
//在生命周期函数中调用异步方法
componentDidMount(){
Store.dispatch(this.getTodoListDatas());
}
//异步获取请求的方法
getTodoListDatas(){
return (dispatch)=>{
axios.get("/data.json")
.then(resp => {
const action = {
type:'axios_getdata',
data:resp.data
}
dispatch(action)
})
}
}
handleStoreChange(){
this.setState(Store.getState());
}
render() {
return (
<div>
<input type='text' value={
this.state.inputValue}></input>
<button>添加</button>
<hr></hr>
<ul>
{
this.state.list.map((item,index)=>{
return (
<li key={
index}>{
item}</li>
);
})}
</ul>
</div>
)
}
}
export default TodoList
第四步 在reducer中接收action信息
const defaultState = {
inputValue:'',
list:[]
}
export default (state = defaultState,action) => {
if(action.type === 'axios_getdata'){
const newState = state;
newState.list = action.data;
return newState;
}
return state
}
2、Redux-thunk中间件 执行原理
2.1、React中间件位置
中间件是在 action----> middlewares--->reducer
,即是在action与reducer中间。
2.2、React中间件的工作原理与流程
中间件的本质,就是对dispatch方法的一个封装,或者说是dispatch方法的一个升级
。
最原始的dispatch方法,他接收到一个对象
之后,会把这个对象传递给store,这就是view中间件的一个情况。
当我们对dispath做了一个升级之后,比如说我们使用了redux-thunk这个中间件,对dispath做了一个升级,这个时候当你调用dispatch方法,给dispatch传递的参数是一个对象的话
,那么这个dispatch就会把这个对象直接传给store,和原始的dispatch方法一样。但是如果给dispatch传递的参数是一个函数
的话,这个时候dispatch方法已经升级了。他就不会把这个函数直接传递给store。,具体流程如下:
- 先执行这个函数,
- 执行完成之后,再去调用store
所以dispatch做了一个事情,他会根据参数的不同,执行不同的事情,如果你参数是对象,那我直接传给store。如果你参数是函数,那就把这个函数执行结束。
原文链接:https://blog.csdn.net/p445098355/article/details/105218217
2.3、常用的中间件
redux- thunk
处理异步操作
使用redux-thunk中间件,改造store.dispatch,使得后者可以接受函数作为参数。redux-saga
处理异步操Redux-promise
返回一个Promise对象redux-log
打印日志
参考地址:https://blog.csdn.net/p445098355/article/details/105218217