2016-01-21 129 views
7

我有一个应用程序使用react @ 0.14,redux @ 3.05,react-router @ 1.0.3和redux-simple-router @ 2.0.2。我试图根据商店状态为我的一些路线配置onEnter转换。过渡钩子成功触发并将新状态推送到我的商店,这会更改网址。但是,页面上呈现的实际组件是来自路由匹配的原始组件处理程序,而不是新网址的新组件处理程序。使用反应路由器和Redux简单路由器onEnter转换不要呈现新路由组件

这里是我的routes.js文件看起来像

export default function configRoutes(store) { 
    const authTransition = function authTransition(location, replaceWith) { 
    const state = store.getState() 
    const user = state.user 

    if (!user.isAuthenticated) { 
     store.dispatch(routeActions.push('/login')) 
    } 
    } 

    return (
    <Route component={App}> 
     <Route path="/" component={Home}/> 
     <Route path="/login" component={Login}/> 
     <Route path="/dashboard" component={Dashboard} onEnter={authTransition}/> 
     <Route path="/workouts" component={Workout} onEnter={authTransition}> 
     <IndexRoute component={WorkoutsView}/> 
     <Route path="/workouts/create" component={WorkoutCreate}/> 
     </Route> 
    </Route> 
) 
} 

这里是被插入到DOM

export default class Root extends React.Component { 
    render() { 
    const { store, history } = this.props 
    const routes = configRoutes(store) 

    return (
     <Provider store={store}> 
     <div> 
      {isDev ? <DevTools /> : null} 
      <Router history={history} children={routes} /> 
     </div> 
     </Provider> 
    ) 
    } 
} 

为了澄清,如果我去“/锻炼”我Root.js组成部分,将触发onEnter authTransition挂钩,调度redux-simple-router push操作,将url更改为“/ login”,但会在页面上显示Workout组件。查看Redux DevTools显示state -> router -> location -> pathname是'/ login'。

状态流程

  1. @@ INIT
  2. @@ ROUTER/UPDATE_LOCATION(/锻炼)
  3. @@ ROUTER/UPDATE_LOCATION(/登录)

AM我传球商店路线不正确?我不明白为什么下一个路由器/ Update_Location不起作用

回答

12

原来你想使用react-router api(替换),而不是redux-simple-router来控制你的转换。

const authTransition = function authTransition(nextState, replace, callback) { 
    const state = store.getState() 
    const user = state.user 

    // todo: in react-router 2.0, you can pass a single object to replace :) 
    if (!user.isAuthenticated) { 
    replace({ nextPathname: nextState.location.pathname }, '/login', nextState.location.query) 
    } 

    callback() 
} 

另外,要小心。我看到了很多文档,其中反应路由器替换了传递单个对象的位置。这是为反应路由器2.0-RC *。如果你使用react-router 1.0,你会想要通过替换3个独立的参数。

+1

你不显示你的进口,你提到'推',但调用'替换'。你能否更多地展示哪些来自哪里?还有你使用哪些历史(从历史或从反应路由器) - 如果1.0我假设历史,但就这样很清楚... –

+0

替换是在反应路由器onEnter回调参数。对不起,认为进口不一定与答案有关,在问题中提到了版本号。 感谢您指出推送。很差的词选择 – Jon

+0

这看起来接近我想解决的问题。商店从哪里来? ...我现在看到它...... – Jome