渲染不等待componentWillMount

时间:2018-06-04 20:34:07

标签: javascript reactjs react-router react-router-dom

如果已经登录,我正在努力重定向到主页。我正在使用ping获取登录信息,如果成功,我将设置一个将在渲染和重定向中检查的状态。但是几秒钟后它会显示登录页面,然后重定向到主页。我做错了什么?

export default class extends Component {
    constructor(props) {
        super(props);
        this.state = {authenticated:false, login: false, loading: true, expand : false, toStudent : false};
        this.handleClick = this.handleClick.bind(this)
    }
    
    async componentWillMount() {
        try{
            
            const response =  await axios.get('http://localhost:3000/api/system/ping', {withCredentials: true});
            await this.setState({'toStudent': true});
            

        }
        catch(err){
            if(err.response.status === 401) {
                console.log('not logged in');
                this.setState({login: true});
            } else if (err.response.status === 500) {
                console.log('card not selected');
                this.setState({authenticated: true});
            }
        }
        
    }
    hideFixedMenu = () => this.setState({fixed: false});
    showFixedMenu = () => this.setState({fixed: true});
    toggleExpand = () => this.setState({expand: !this.state.expand});
    handleClick () {
        console.log("clicked")
        window.location.href = "http://localhost:3000/auth/github";
    }


    render() {
        const {children} = this.props;
        const {fixed} = this.state;
        if (this.state.toStudent) {
            console.log("Routing to student")
            return <Redirect push to={{pathname: "/student"}}/>;
        }
        
        return (
            <Responsive>
                <Visibility once={false} onBottomPassed={this.showFixedMenu} onBottomPassedReverse={this.hideFixedMenu}>
                    <Segment inverted textAlign='center' style={{padding: '1em 0em'}} vertical>
                        <HeadingComponent/>

                    </Segment>
                    
                    
                    <Segment inverted textAlign='center' style={{height: '500px', padding: '5em 5em',}} vertical>
                    {!this.state.authenticated && <Button icon="github" primary size='huge' content="Athenticate with github" onClick={this.handleClick} style={{margin: '1em'}}/>}
                    {this.state.authenticated && !this.state.login && <BadgesComponent click={this.toggleExpand}/>}
                    {this.state.expand && <LoginComponent onBackClick={this.toggleExpand}/>}
                    </Segment>

                </Visibility>

                <ContentComponent/>

            </Responsive>


        );
    }
    
}

1 个答案:

答案 0 :(得分:3)

您将componentWillMount声明为async。但是,React执行生命周期钩子,但不等待它完成。您应该呈现显示“加载指示符”的页面,并在componentDidMount中获取您的数据。看看这里:Asynchronous call in componentWillMount finishes after render method

componentWillMountdeprecated

相关问题