上文在 componentDidMount 中定义了axios 中请求,或把一些非常复杂的逻辑都放在这个里面的时候,这个组件会显得很冗余。
所以遇到这种异步请求或复杂的逻辑,应该移除到其他地方进行管理。可移到 Redux-thunk 这个中间件,可使我们把 异步请求 和 复杂的逻辑放到action 里去处理。
一、 使用 redux-thunk
安装和使用参照:
https://github.com/reduxjs/redux-thunk
我这用的 yarn 安装 :yarn add redux-thunk
然后重启项目。
在创建store 的时候要使用这个中间件。
引入[applyMiddleware()](https://redux.js.org/api/applymiddleware) 的方法。
引入 thunk
在 createStore() 方法传递第二个参数:applyMiddleware(thunk) 使用thunk 这个中间件
// store/index.jsimport { createStore, applyMiddleware } from 'redux';import thunk from 'redux-thunk';import reducer from './reducer'const store = createStore(reducer,// 用了 thunk 和 REDUX_REDUX_DEVTOOLS_EXTENSION 的中间件,applyMiddleware(thunk)export default store;
解决 thunk 和 REDUX_REDUX_DEVTOOLS_EXTENSION 的这两个中间件 一起使用的问题:
https://github.com/zalmoxisus/redux-devtools-extension
拷贝过来,修改后:
// store/index.jsimport { createStore, applyMiddleware, compose } from 'redux';import thunk from 'redux-thunk';import reducer from './reducer'// 解决 thunk 和 REDUX_REDUX_DEVTOOLS_EXTENSION 的中间件 一起使用的问题const composeEnhancers =window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({// componse 函数要在上面引入进来}) : compose;const enhancer = composeEnhancers(applyMiddleware(thunk),);const store = createStore(reducer,enhancer);export default store;
再重启。以上就使用好了 redux-thunk 了,可开始编写代码了。
二、围绕redux-thunk开始编写代码
就可以把异步操作的代码移到 action 里去了,actionCreator return 结果 可以是一个函数了,函数
组件中的action 可以是一个函数了。:const action = getTodoList(); 以前只能是对象。
当你在 actionCreator 中,当你调用里面的一个函数,生成的内容是函数的action 的时候,这个函数接收到store的dispatch 方法,所以直接传递,下面就可以使用了,
actionCreato.js
import axios from 'axios';export const getTodoList = () => {return (dispatch) => {axios.get('/list.json').then((res) => {const data = res.data;const action = initListAction(data);//action 派发dispatch(action);})}}
TodoList.js
import { getInputChangeAction, getAddTodoItem, getDeleteItem, getTodoList } from './store/actionCreator';
componentDidMount() {const action = getTodoList();store.dispatch(action)console.log(action);}
实现效果:
