react-router-redux将历史记录传递给中间件

时间:2017-10-22 08:32:06

标签: javascript reactjs react-redux history.js react-router-redux

我有以下文件:

configureStore.js

import { createStore, applyMiddleware, compose, combineReducers } from 'redux'
import { routerReducer } from 'react-router-redux'
import middleware from './middleware'

export default (initialState) => createStore(
  combineReducers({
    ...
    router: routerReducer
  }),
  initialState,
  compose(applyMiddleware(...middleware))
)

middleware.js

import { routerMiddleware } from 'react-router-redux'

export default [
  ...
  routerMiddleware(/* How do I access history here? */) //<-- history
]

index.js

import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import { ConnectedRouter as Router } from 'react-router-redux'
import { createBrowserHistory } from 'history'
import App from './App'
import configureStore from './configureStore'

const history = createBrowserHistory()

ReactDOM.render(
  <Provider store={configureStore()}>
    <Router history={history}> //<-- history
      <App />
    </Router>
  </Provider>,
  document.getElementById('root')
)

版本:&#34;历史&#34;:&#34; 4.7.2&#34;,&#34; react-redux&#34;:&#34; 5.0.6&#34;,&#34 ; react-router-redux&#34;:&#34; 5.0.0-alpha.8&#34;,&#34; redux&#34;:&#34; 3.7.2&#34;

所以我必须将历史记录传递给<Router>routerMiddleware()。有没有简单的方法可以访问middleware.js中创建的历史记录?

1 个答案:

答案 0 :(得分:1)

一个简单的答案是否定的。但是在JS中,一切都是可能的,即使它不是一件好事。 您可以将历史记录传递给函数,然后返回路由器中间件。

// middleware.js

import { routerMiddleware } from "react-router-redux";


let createMiddleWare = ({history}) => { [
  routerMiddleware(history); //<-- history
])