【发布时间】:2020-06-08 19:54:39
【问题描述】:
正如官方文档所说,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
};
}
我会试试这个,因为这对我来说确实有意义。
【问题讨论】:
-
你有没有考虑把它放到componentDidMount()中?
-
我已经考虑过了,但如果这是个好主意,它会在文档中提到。
-
我认为在你的构造函数中设置状态不是一个好主意,stackoverflow.com/questions/34961853/…
-
注意事项不要将您的身份验证令牌存储在本地存储中,否则会将其暴露于 XSS 攻击
标签: javascript reactjs