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 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...
react 本身提供了克隆组件的方法,但是平时开发中可能很少使...
mobx 是一个简单可扩展的状态管理库,中文官网链接。小编在接...
我们在平常的开发中不可避免的会有很多列表渲染逻辑,在 pc ...