gpt4 book ai didi

javascript - componentWillMount 已弃用

转载 作者:行者123 更新时间:2023-11-28 03:08:24 29 4
gpt4 key购买 nike

正如官方文档所说, componentWillMount 现已弃用,建议放置用于此生命周期方法的任何代码都放入构造函数中。

老实说我不知道​​该怎么做。我已经得到了用于 componentWillMount 的代码但我应该如何将它实现到构造函数中:

if (window.localStorage.getItem("authToken"))
this.setState({ isAuthenticated: true });

我是这样的:

constructor() {
super();
this.state = {
users: [],
username: "",
email: "",
title: "something",
isAuthenticated: false
};
if (window.localStorage.getItem("authToken"))
this.setState({ isAuthenticated: true });
}

但该条件在应该触发时并未触发。条件语句应该如何在构造函数中工作?

非常感谢任何指导。

编辑:

constructor() {
super();
this.state = {
users: [],
username: "",
email: "",
title: "something",
isAuthenticated: window.localStorage.getItem("authToken") ? true : false
};
}

我会尝试这个,因为这对我来说确实有意义。

最佳答案

您无法期望 componentWillMount 的确切流程,并且需要您以稍微不同的方式思考。

你可以做到这一点。


componentDidMount() {
if (window.localStorage.getItem("authToken"))
this.setState({ isAuthenticated: true });
}


render() {
// Since this function will be called before
// componentDidMount, handle the false case here

if (!this.state.isAuthenticated) {
return null; // or any fallback UI for unAuthenticated user
}

return (
// the original UI
)
}


关于javascript - componentWillMount 已弃用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60388563/

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