生命周期方法中的不支持状态更新¶
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
三个内置的 React 组件方法 setState
、replaceState
和 forceUpdate
可以异步更新组件的状态。但是,在组件生命周期的某些点调用这些方法是不推荐的。
例如,在调用 render
期间调用其中一个状态更新方法将导致 React 抛出异常,因为 render
方法必须是纯函数。从组件的构造函数调用其中一个状态更新方法也是禁止的,因为组件此时尚未挂载。三个组件方法 componentDidUpdate
、componentWillUpdate
和 shouldComponentUpdate
允许调用状态更新方法,但前提是这些调用是条件性的。
建议¶
仅当 React 组件的生命周期允许时,才调用其上的状态更新方法。
示例¶
以下示例使用 setState
从 React 组件的构造函数更新 this.state
的 counter
属性
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>
}
}
参考资料¶
React 参考:React.Component.
React 快速入门:状态和生命周期.