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

前端之家收集整理的这篇文章主要介绍了reactjs – 如何在React-Router onEnter中保留存储/调度?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我没有使用Redux-Router(也许我必须?)但是我的路由器被Provider包装,商店正在传递给它.

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

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

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

任何onEnter / onExit函数也在那里定义,因此他们可以访问该store参数并可以调度()东西.

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>
  );
}

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

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

  next();
}

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

猜你在找的React相关文章