CodeQL 文档

生命周期方法中的不支持状态更新

ID: js/react/unsupported-state-update-in-lifecycle-method
Kind: problem
Security severity: 
Severity: warning
Precision: high
Tags:
   - reliability
   - frameworks/react
Query suites:
   - javascript-security-and-quality.qls

点击查看 CodeQL 代码库中的查询

三个内置的 React 组件方法 setStatereplaceStateforceUpdate 可以异步更新组件的状态。但是,在组件生命周期的某些点调用这些方法是不推荐的。

例如,在调用 render 期间调用其中一个状态更新方法将导致 React 抛出异常,因为 render 方法必须是纯函数。从组件的构造函数调用其中一个状态更新方法也是禁止的,因为组件此时尚未挂载。三个组件方法 componentDidUpdatecomponentWillUpdateshouldComponentUpdate 允许调用状态更新方法,但前提是这些调用是条件性的。

建议

仅当 React 组件的生命周期允许时,才调用其上的状态更新方法。

示例

以下示例使用 setState 从 React 组件的构造函数更新 this.statecounter 属性

class MyComponent extends React.Component {

    constructor(props) {
        super(props)
        this.setState({
            counter: 0
        })

    }

    render() {
        return <div>{this.state.counter}</div>
    }

}

改为用赋值替换对 setState 的调用

class MyComponent extends React.Component {

    constructor(props) {
        super(props)
        this.state.counter = 0;
    }

    render() {
        return <div>{this.state.counter}</div>
    }

}

参考资料

  • ©GitHub, Inc.
  • 条款
  • 隐私