我没有使用Redux-Router(也许我必须这么做?)但我的路由器被Provider包装,商店正在传递给它。
我想在onEnter
处理程序中读取状态和调度。
答案 0 :(得分: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>
);
}
在服务器端(对我来说是express.js)我很早就用中间件建立了一个redux商店。这样的事情。
server.use((req, res, next) => {
const createStoreWithMiddleware = applyMiddleware(
thunkMiddleware
)(createStore);
res.store = createStoreWithMiddleware(rootReducer);
next();
}
现在,商店已附加到响应对象,可供其他中间件/路由使用。他们可以获得状态(res.store.getState()
)并调度以更新状态。
答案 1 :(得分:3)
只需在单独的文件中创建您的redux商店,并在需要时将其需要。
// store.js
import { createStore } from 'redux'
import todoApp from './reducers'
export default createStore(todoApp);
// the file where you define your routes and onEnter
import { render } from 'react-dom';
import { Router, Route } from 'react-router';
import store, { dispatch } from './store.js';
function enterHandler(){
dispatch(allTheGoodStuff);
}
render(
<Router>
<Route onEnter={ enterHandler } ...
)