8

这是我的代码

import React        from "react";
import ReactDOM     from "react-dom";
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import "normalize.css/normalize.css"
import  "./styles/styles.scss";
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import reduxThunk from 'redux-thunk';
import { composeWithDevTools } from 'redux-devtools-extension';

import AppRouter from './routers/AppRouter';
import reducers from './reducers';
import {AUTH_USER} from "./actions/types";

//
const createStoreWithMiddleware =  applyMiddleware(reduxThunk)(createStore);
const store = createStoreWithMiddleware(reducers);


const token = localStorage.getItem('token');
if(token){
    store.dispatch({type:AUTH_USER});
}

ReactDOM.render(
    <Provider store={store}>
        <AppRouter />
    </Provider>
    , document.getElementById('app'));

所以我想使用来自 npm 的 redux-devtools-extension 包

我如何使用 createStoreWithMiddleware 实现

4

1 回答 1

25

composeWithDevTools只需在第一次导入时用 .Like包装中间件:

import { composeWithDevTools } from 'redux-devtools-extension';

将所有中间件添加到一个数组中。现在只有一个。

const middleware = [
    reduxThunk,
];

然后代替createStoreWithMiddleWare

const store = createStore(reducers, composeWithDevTools(
  applyMiddleware(...middleware),
  // other store enhancers if any
));

所以代码变成了:

import React        from "react";
import ReactDOM     from "react-dom";
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import "normalize.css/normalize.css"
import  "./styles/styles.scss";
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import reduxThunk from 'redux-thunk';
import { composeWithDevTools } from 'redux-devtools-extension';

import AppRouter from './routers/AppRouter';
import reducers from './reducers';
import {AUTH_USER} from "./actions/types";


const middleware = [
    reduxThunk,
];

const store = createStore(reducers, composeWithDevTools(
applyMiddleware(...middleware),
// other store enhancers if any
));


const token = localStorage.getItem('token');
if(token){
    store.dispatch({type:AUTH_USER});
}

ReactDOM.render(
    <Provider store={store}>
        <AppRouter />
    </Provider>
    , document.getElementById('app'));

尚未测试,但应该可以工作。

于 2018-05-17T07:37:46.370 回答