导致的问题
- 在state改变时组件不会重新渲染.
- 在未来某个时候如果通过setState改变了state, 那么这次未通过setState去改变的state将会同样生效.
class SampleComponent extends Component {
constructor(props) {
super(props);
this.state = {
items: ['foo', 'bar']
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
// 坏实践: 我们手动更改了state而不是通过setState函数.
this.state.items.push('lorem');
this.setState({
items: this.state.items
});
}
render() {
return (
<div>
{this.state.items.length}
<button onClick={this.handleClick}>+</button>
</div>
)
}
}
class SampleComponent extends Component {
constructor(props) {
super(props);
this.state = {
items: ['foo', 'bar']
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
// 我们使用了setState()方法来更新state, 组件将会在state更改后被更新.
this.setState({
items: this.state.items.concat('lorem')
});
}
render() {
return (
<div>
{this.state.items.length}
<button onClick={this.handleClick}>+</button>
</div>
)
}
}
React Design Patterns and best practices by Michele Bertoli.