当用户未使用 React 和 Redux 登录时,我正在努力弄清楚如何正确重定向到登录页面。
目前,在组件的构造函数中,我检查是否设置了用户名,如果没有,我使用提供的 routeActionsredux-simple-router重定向到登录页面。但是,我收到此错误:
Warning: setState(...): Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.
我知道应该避免在渲染函数内部设置状态。但我不确定应该在哪里检测和重定向。我也尝试过检查 and 中的身份验证状态componentWillReceiveProps,ComponentWillMount但没有运气。
// WordListContainer.js
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import {routeActions} from 'redux-simple-router';
import WordList from '../components/Words/WordList';
import {addWord, editWord, deleteWord, fetchWords} from '../actions/words';
function mapStateToProps(state) {
return {
auth: state.auth,
words: state.words
};
}
function mapDispatchToProps(dispatch) {
return {
router: bindActionCreators(routeActions, dispatch),
actions: bindActionCreators({
addWord, editWord, deleteWord, fetchWords
}, dispatch)
};
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(WordList);
和
// WordList.js
import React, {Component} from 'react';
import {Link} from 'react-router';
import WordListItem from './WordListItem';
export default class WordList extends Component {
constructor(props) {
super(props);
if(!this.props.auth.username) {
// This redirection causes the error
this.props.router.push('/login');
}
}
render() {
...
}
}
有没有一个好地方可以在尝试渲染组件之前检查状态和重定向?也许以某种方式使用容器对象,虽然我不太确定如何在我可以访问状态和调度的地方做到这一点。