未用或未定义的状态属性¶
ID: js/react/unused-or-undefined-state-property
Kind: problem
Security severity:
Severity: warning
Precision: high
Tags:
- correctness
- reliability
- frameworks/react
Query suites:
- javascript-security-and-quality.qls
未用或未定义的 React 组件状态属性会导致错误,或使代码难以阅读和理解。任何用于初始化未用状态属性的计算都是浪费的,这可能会导致性能问题。任何对未定义的组件状态属性的访问都会简单地评估为 undefined
,这可能会出乎意料。
建议¶
删除未用的组件状态属性。为未定义的组件状态属性赋值。
示例¶
在下面的代码中,React 组件 Clock
试图在 render
方法中显示当前时间。
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = { };
}
render() {
// BAD: this.state.date is undefined
var now = this.state.date.toLocaleTimeString();
return (
<div>
<h2>The time is {now}.</h2>
</div>
);
}
}
但是,由于没有对 this.state.date
赋值,因此 render
方法在尝试访问 undefined
值的 toLocaleString
属性时会抛出异常。为了避免此异常,请在使用之前为 date
属性赋值。
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = { date: new Date() };
}
render() {
// GOOD: this.state.date is defined above
var now = this.state.date.toLocaleTimeString()
return (
<div>
<h2>The time is {now}.</h2>
</div>
);
}
}