【问题标题】:<Provider /> outside or <Router /> outside>?<Provider /> 外部还是 <Router /> 外部>?
【发布时间】:2017-05-25 02:35:33
【问题描述】:

通常(react-router + redux):

<Provider store={store}>
 <Router>
    <App />
 </Router>
</Provider>

为什么不反过来呢?

<Router>
  <Provider store={store}>
    <App />
  </Provider>
</Router>

后续问题:要设置身份验证,当触发LOGIN_SUCCESS 操作时,我们需要将返回的令牌保存到window.localStorage重定向页面。所以我在 redux 中间件中编写了成功处理程序:

const localStorageMiddleware = store => next => action => {
  if (action.type === 'LOGIN_SUCCESS') {
    if (!action.payload.error) {
      window.localStorage.setItem('jwt', action.payload.token)
    }
  } else if (action.type === 'LOGOUT_SUCCESS') {
    window.localStorage.setItem('jwt', '')
  }
  next(action)
}

然后我觉得需要访问history.push 进行重定向(这就是为什么我问第一个问题,试图在redux 代码中访问location),我该怎么做?

【问题讨论】:

  • 你使用的是什么版本的react-router

标签: reactjs redux react-router


【解决方案1】:

试试这个:

<Provider store={store}>
 <Router>
    <App />
 </Router>
</Provider>

重定向:

// top-most line of the reducer
import { browserHistory } from 'react-router';

const localStorageMiddleware = store => next => action => {
  if (action.type === 'LOGIN_SUCCESS') {
    if (!action.payload.error) {
      window.localStorage.setItem('jwt', action.payload.token);
      browserHistory.push('/');
    }
  } else if (action.type === 'LOGOUT_SUCCESS') {
    window.localStorage.setItem('jwt', '')
  }
  next(action)
}

我会将逻辑放到 actions 文件中,而不是 reducers

【讨论】:

  • 酷。顺便说一句,在路由器周围包装提供者,而不是其他方式?
  • 我使用 promise 中间件来处理动作,所以我不能在动作中做 .then() 的东西,对吧?
猜你喜欢
  • 2014-02-03
  • 1970-01-01
  • 1970-01-01
  • 2017-08-12
  • 2010-11-15
  • 1970-01-01
  • 2012-07-18
  • 2011-06-26
相关资源
最近更新 更多