ReduxThunk
Redux Thunk 可以使 Redux 的 Action 不只是返回对象,也可以是一个函数。该函数在 Component 执行 dispatch(atcion) 时会自动执行。
使用原因:使用 Redux Thunk 替换在组件生命周期函数中,使用异步函数的问题。
解决因生命周期函数所需执行的内容过多问题。
Redux Data Flow
Redux 的数据流程图:
引入依赖
yarn add redux-thunk
Redux 使用 Redux-thunk 中间件
在创建 Redux 的 Store 时,应用所需使用的中间件。
来源于 github:redux-thunk
import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import rootReducer from "./reducers/index";
// Note: this API requires redux@>=3.1.0
const store = createStore(rootReducer, applyMiddleware(thunk));
如果需要使用多个中间件,这里使用 Redux-DevTools 和 Redux-Thunk 两个中间件做演示,请使用下面的方式:
来源于 github:redux-devtools-extension
import { createStore, applyMiddleware, compose } from "redux";
import reducer from "./reducer";
import thunk from "redux-thunk";
const composeEnhancers =
typeof window === "object" && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({})
: compose;
const enhancer = composeEnhancers(
applyMiddleware(thunk) // 如果有其他中间件,可以在这里引入
);
const store = createStore(reducer, enhancer);
export default store;