ReactJS组件重定向停止当前组件

ReactJS组件重定向停止当前组件,reactjs,Reactjs,所以在加载一个组件时,我想检查一个变量,如果该变量存在,我想停止加载该组件,并将它们重定向回主页。下面的代码可以正常工作,但由于重定向用户的组件仍在尝试加载,因此出现堆栈跟踪错误 class Repo extends Component { constructor(props) { super(props); this.state = { repo: {} }; } componentWillMount() { if (localSt

所以在加载一个组件时,我想检查一个变量,如果该变量存在,我想停止加载该组件,并将它们重定向回主页。下面的代码可以正常工作,但由于重定向用户的组件仍在尝试加载,因此出现堆栈跟踪错误

class Repo extends Component {
  constructor(props) {
    super(props);

    this.state = {
      repo: {}
    };

  }

  componentWillMount() {
    if (localStorage.getItem('login'))
      this.props.history.push('/');
  }
}

想法?

如果您将逻辑移动到
componentDidMount

应该可以工作,如果该变量存在,您可以只渲染组件。沿着这条线的东西

render() {
  if (localStorage.getItem('login')) {
    return (
      <Redirect to={{
        pathname: '/',
        state: { from: routeProps.location }
      }}/>
    );
  } else {
    // Normal rendering here.
  }
}
render(){
if(localStorage.getItem('login')){
返回(
);
}否则{
//这里是正常渲染。
}
}

no,仍然收到警告:只能更新已安装或正在安装的组件。这通常意味着您在未安装的组件上调用setState、replaceState或forceUpdate。这是禁止的。