【问题标题】:componentWillMount is deprecated不推荐使用 componentWillMount
【发布时间】: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


【解决方案1】:

您不能期望 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
  )
}


【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    • 2012-11-14
    • 1970-01-01
    • 2019-11-08
    • 2019-11-08
    • 2020-01-03
    • 2011-12-02
    相关资源
    最近更新 更多