如何在React-Router onEnter中保留存储/调度?

kjs*_*js3 6 reactjs react-router redux

我没有使用Redux-Router(也许我必须?)但是我的路由器被Provider包装,商店正在传递给它.

我想在onEnter处理程序中读取状态和调度.

kjs*_*js3 7

我只是将我的路由包装在一个返回它们的函数中.

这允许您将redux存储作为参数传递

任何onEnter/ onExit函数也在那里定义,因此他们可以访问该store参数并且可以dispatch()填充.

import React from 'react'
import { IndexRoute, Route } from 'react-router'

import App from './components/app'
import FourOhFour from './components/pages/404'
import Home from './components/home'
import LogIn from './components/account/log_in'
import ResetPassword from './components/account/reset_password'
import SignUp from './components/account/sign_up'

export function getRoutes (store) {
  function doSomething (thing) {
    store.dispatch(addToDoActionCreator(thing))
  }

  function authenticate (nextState, replaceState) {
    const { currentUser } = store.getState();

    if ( !currentUser ) {
      replaceState(null, '/log-in');
    }
  }

  return (
    <Route path='/' component={App}>
      <IndexRoute component={Home} onEnter={(nextState, replaceState)=>{doSomething('get coffee')}} />

      <Route path='log-in' component={LogIn} onEnter={authenticate} />
      <Route path='sign-up' component={SignUp} />
      <Route path='reset-password' component={ResetPassword} />

      <Route path="*" component={FourOhFour}/>
    </Route>
  );
}
Run Code Online (Sandbox Code Playgroud)

在服务器端(对我来说是express.js)我很早就用中间件建立了一个redux商店.像这样的东西.

server.use((req, res, next) => {
  const createStoreWithMiddleware = applyMiddleware(
    thunkMiddleware
  )(createStore);
  res.store = createStoreWithMiddleware(rootReducer);

  next();
}
Run Code Online (Sandbox Code Playgroud)

所以现在商店附加到响应对象,并且可以被其他中间件/路由使用.他们可以获得state(res.store.getState())和dispatch来更新状态.