Redux Devtool和Redux-thunk冲突的解决办法

一、安装Redux Devtool

 以谷歌浏览器为例,右上角——更多工具——扩展程序——打开chrome网上应用商店(这里可能需要翻墙)——搜索redux.devtools——添加至chrome(我已经安装了,所以是“评分”)

  

安装完成后F12打开Redux就可以看到了。

在仓库文件(定义store的JS文件)中设置:

1 import { createStore, compose } from 'redux';
2 import reducer from './reducer';
3 
4 const store = createStore(reducer, window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;);
5 
6 export default store;

二、安装Redux-thunk

运行命令“npm install redux-thunk”就可以安装了。

在仓库文件(定义store的JS文件)中设置:

1 import { createStore, applyMiddleware} from 'redux';
2 import reducer from './reducer';
3 import thunk from 'redux-thunk';
4 
5 const store = createStore(reducer, applyMiddleware(thunk));
6 
7 export default store;

三、解决Redux Devtool和Redux-thunk同时引用造成的冲突

 如果Redux Devtool和Redux-thunk想要同时配置就会会产生冲突,因为他们都只能写在createStore()方法的第二个参数里,仓库文件(定义store的JS文件)必须写成下面这样:

 1 import { createStore, applyMiddleware, compose } from 'redux';
 2 //从redux中引入applyMiddleware和compose
 3 import reducer from './reducer';
 4 //引入reducer
 5 import thunk from 'redux-thunk';
 6 //引入redux-thunk中间件
 7 
 8 const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;
 9 //Redux Devtools配置
10 
11 const enhancer = composeEnhancers(applyMiddleware(thunk));
12 //将Redux Devtools和redux-thunk合并
13 
14 const store = createStore(reducer, enhancer);
15 //调用createStore方法创建仓库,并传入reducer和enhancer
16 
17 export default store;

关于第8行,官方文档的写法有所不同,GitHub链接:https://github.com/zalmoxisus/redux-devtools-extension#12-advanced-store-setup。如下:

typeof window ==='object'&&window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;

由于我写的是网页,因此typeof window ==='object'肯定是成立的,所以删除了这段。

猜你喜欢

转载自www.cnblogs.com/hejing-work/p/11772433.html