小编典典

使用React Router和Redux Simple Router进行onEnter转换不会渲染新路由的组件

reactjs

我有一个使用react @ 0.14,redux @ 3.05,react-router @ 1.0.3和redux-simple-router @
2.0.2的应用程序。我正在尝试根据商店状态为我的一些路线配置onEnter过渡。过渡挂钩成功触发并将新状态推送到我的商店,这将更改URL。但是,页面上呈现的实际组件是路由匹配中的原始组件处理程序,而不是新url的新组件处理程序。

这是我的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>
  )
}

这是我Root.js插入到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>
    )
  }
}

为了澄清,如果我转到“ / workouts”,它将触发onEnter authTransition钩子,调度redux-simple-
router推送操作,将url更改为“ / login”,但将在页面上显示Workout组件。在Redux DevTools中查看显示state -> router -> location -> pathname为’/ login’。

状态流是

  1. @@在里面
  2. @@ ROUTER / UPDATE_LOCATION(/锻炼)
  3. @@ ROUTER / UPDATE_LOCATION(/登录)

我是否将商店错误地传递到路线?我不知道为什么下一个Router / Update_Location不起作用


阅读 274

收藏
2020-07-22

共1个答案

小编典典

事实证明,您想使用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()
}

另外,要小心。我看到了很多文档,这些文档用于在您传递单个对象的地方替换react-router。这是针对react-router 2.0-rc
*的。如果您使用react-router 1.0,则需要传递replace 3个单独的参数。

2020-07-22