通常(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}}
},我该怎么办所以?
答案 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
。