首页 > 解决方案 > 这个 componentWillMount 案例的替代方案?

问题描述

我正在尝试重构一些旧代码。

componentWillMount已被弃用。

我如何将它在这里重构为其他东西?

class Detail extends React.Component{

constructor(props) {
    super(props);

    this.state = {
        logged_out_redirect: true
    };
}   

componentWillMount() {  //<------ this lifecycle method has been deprecated, how do I replace it?

    if (localStorage.getItem("JWT")) {
        this.setState({logged_out_redirect: false});
    }
}

render() {

    if (this.state.logged_out_redirect) {
        return (<Redirect to={"/login"}/>)
    }

    return (        )

}

}

标签: reactjsreact-lifecycle

解决方案


在这种情况下(取决于你想要做什么componentWillMount)。你不能把它放在你的constructor()

constructor(props) {
  super(props);

  this.state = {
    logged_out_redirect: localStorage.getItem("JWT") ? false : true
  };
}

推荐阅读