【问题标题】:React-router-redux error when creating store with middleware使用中间件创建商店时出现 React-router-redux 错误
【发布时间】:2017-07-01 19:50:41
【问题描述】:

我是 react-redux 的新手,并试图遵循一个有点旧的教程,所以当我尝试运行这段代码时,我得到了错误:

未捕获的错误:预期路由状态可用state.routing 或您可以在syncHistoryWithStore() 选项中指定为selectLocationState 的自定义表达式。确保您已通过 combineReducers 或您用来隔离减速器的任何方法将 routerReducer 添加到商店的减速器中。

有什么建议吗? :)

index.js

import React from 'react'
import ReactDOM from "react-dom"
import { createStore, applyMiddleware } from 'redux'
import { Provider } from 'react-redux'
import { Router, Route, browserHistory } from 'react-router'
import { syncHistoryWithStore, routerReducer } from 'react-router-redux'
import App from './containers/App'
import rootReducer from './reducers/reducers'
import thunkMiddleware from 'redux-thunk'
import api from './middleware/api'

let createStoreWithMiddleware = applyMiddleware(thunkMiddleware, api)(createStore)

let store = createStoreWithMiddleware(rootReducer)

let history = syncHistoryWithStore(browserHistory, store)

let rootElement = document.getElementById('root')

ReactDOM.render(
  <Provider store={store}>
    <Router history={history}>
      <Route path='/' component={App} />
    </Router>
  </Provider>,
  rootElement
)

我的 reducers.js 看起来像这样:

import { combineReducers } from 'redux'

import Auth from './auth'
import Quotes from './quotes'

const rootReducer = combineReducers({
    auth: Auth,
    quotes: Quotes
})

export default rootReducer

【问题讨论】:

  • 你能把你的./reducers/reducers文件包括进来吗?

标签: reactjs react-router store react-redux history


【解决方案1】:

您必须添加 routerReducer() 才能在 react-router-redux 中进行同步。

这个 reducer 函数存储来自历史的位置更新。如果你 使用 combineReducers,它应该嵌套在路由键下。

在您的组合减速器中包含以下内容。

import { routerReducer } from 'react-router-redux';

export const reducers = combineReducers({
  ...  // other reducers
  routing: routerReducer
});

所以你的 reducers 文件看起来像:

import { routerReducer } from 'react-router-redux';
import { combineReducers } from 'redux'

import Auth from './auth'
import Quotes from './quotes'

const rootReducer = combineReducers({
    auth: Auth,
    quotes: Quotes,
    routing: routerReducer
})

export default rootReducer

【讨论】:

  • 是的,谢谢!我仍然有早先的建议“撰写”,所以它抛出了错误,但现在它适用于此:)
猜你喜欢
  • 2017-05-29
  • 2019-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多