此组件的替代方法WillMount案例?

时间:2019-04-06 03:36:59

标签: reactjs react-lifecycle

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

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 (        )

}

}

3 个答案:

答案 0 :(得分:1)

在这种情况下(取决于大小写,您在componentWillMount中尝试执行的操作)。您不能将其放入constructor()

constructor(props) {
  super(props);

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

答案 1 :(得分:1)

您可以尝试使用getDerivedStateFromProps。这将是第一次调用,并随后进行任何更新。

static getDerivedStateFromProps(props, state) {
    if (localStorage.getItem("JWT") && state.logged_out_redirect) {
        return {logged_out_redirect: false};
    }
    return null;
}

答案 2 :(得分:0)

您可以将其替换为SELECT word.lemma ,case when r = 1 synset.definition else null end as definition ,synset.pos ,sampletable.sample FROM ( SELECT word.lemma ,synset.definition ,synset.pos ,sampletable.sample ,RANK() OVER (PARTITION BY synset.definition ORDER BY synset.definition) r FROM ( SELECT word.lemma, synset.definition, synset.pos, sampletable.sample FROM word LEFT JOIN sense ON word.wordid = sense.wordid LEFT JOIN synset ON sense.synsetid = synset.synsetid LEFT JOIN sampletable ON synset.synsetid = sampletable.synsetid WHERE word.lemma = 'good' ) t )t1;

componenDidMount