gpt4 book ai didi

javascript - 渲染不等待 componentWillMount

转载 作者:行者123 更新时间:2023-11-28 17:29:56 25 4
gpt4 key购买 nike

如果已经登录,我正在努力重定向到主页。我正在使用 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>


);
}

}

最佳答案

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

componentWillMountdeprecated

关于javascript - 渲染不等待 componentWillMount,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50688362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com