如果在react-router中重定向到Login,保存“next pathname”的位置?

时间:2016-07-31 11:18:34

标签: react-router react-router-redux redux-saga

我使用react-router和react-router-redux,如果他试图访问需要登录的页面而不登录,我会将用户重定向到Login页面:

<Route path="/react/myprofile" component={MyProfile} onEnter={requireAuth} /></Route>


function requireAuth(nextState, replace) {
   const state_user = store.getState().auth.user;
   if (!state_user) {
     console.log('not logged in, redirect')
     replace({
       pathname: '/react/login',
       state: { nextPathname: nextState.location.pathname }
     })
   }
}

用户登录后,我会将用户重定向到“/ react / myprofile”:在我的redux-saga中,我会执行以下操作:

const route_state = get routing state from the store;
redirectTo(route_state.locationBeforeTransitions.state.nextPathname);

如上所述,我必须从route_state.locationBeforeTransitions.state.nextPathname检索信息,它太冗长了,这样做似乎很奇怪。

我想知道是否有更好的方法来做到这一点?感谢。

1 个答案:

答案 0 :(得分:1)

您可以创建一个选择器来提取相关的状态,并将其与您的传奇中的select效果一起使用

// for example in some file selectors
export const nextPathSelector = state => ...

// in some sagas.js file
import { nextPathSelector } from './selectors'
import { call, select, ... } from 'redux-saga/effects'

function* saga() {
  ...
  const nextPath = yield select( nextPathSelector )
  yield call(redirectTo, nextPath)
}

使用选择器使您的传奇与状态形状无关。使用select效果,您可以测试传奇的逻辑,而无需调整整个商店。例如

const gen = saga()

assert.deepEqual(
   gen.next().value,
  select( nextPathSelector )
)

assert.deepEqual(
   gen.next('dummy-path').value,
   call(redirectTo, 'dummy-path')
)