代码之家  ›  专栏  ›  技术社区  ›  bier hier

如何重构componentWillMount事件中的代码?

  •  0
  • bier hier  · 技术社区  · 7 年前

    我正在重构我的reactjs(react v16.0.0)组件,并尝试将componentWillMount事件的名称更改为componentDidMount,因为有人反对。以下是原始代码:

    componentWillMount() {
          this.setState({
            myVar: this.getValue(),
          });
        }
    }
    

    当我将其更改为componentDidMount时,我得到一个eslint错误:

    Do not use setState in componentDidMount
    

    我怎样才能避开这件事?如何修复此eslint错误?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Yulio Aleman Jimenez    7 年前

    您可以尝试不直接在服务器上设置状态 componentDidMount

    componentDidMount() {
        this.onMount(this.getValue());
    }
    
    onMount(newValue){
        this.setState({
            myVar: newValue
        });
    }
    

    你也可以禁用你的 eslint