<provider> outside或<router> outside&gt;?

时间:2017-05-25 02:35:34

标签: reactjs redux react-router

通常(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进行重定向(这就是为什么我问第一个问题,试图访问location redux代码内的{{post.title}}},我该怎么办所以?

1 个答案:

答案 0 :(得分: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