同时使用redux-devtools插件和redux-thunk如何编写store和reducer
Redux-thunk是Rudex的一个中间件。
使用Redux-thunk,首先要安装Redux-thunk。
npm install --save redux-thunk
在创建store的时候,来使用redux-thunk。
// 创建store
import { createStore, applyMiddleware, compose } from "redux";
import thunk from "redux-thunk";
import reducer from "./reducer";
// 创建数据公共存储仓库
// 调用createStore即可创建一个store
// 创建store的时候使用redux-thunk这个中间件
// 实际上,chrome中的插件REDUX_DEVTOOLS也是一个redux中间件
// 在github redux-devtools-extension中有同时使用这两个中间件的使用方法。如下
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({})
: compose;
const enhancer = composeEnhancers(applyMiddleware(thunk));
const store = createStore(reducer, enhancer);
export default store;
注意,是在创建Redux的store的时候使用了Redux的中间件。无论是Redux-thunk还是redux-devtools都是Redux的中间件。
以上代码完成了一件事:安装了thunk,并且在Redux创建的时候使用了thunk。
reducer的编写:
// reducer.js
const defaultState = {};
const reducer = (state = defaultState, action) => {
// 此处编写自己关于action或者其他代码
return state;
};
export default reducer;