【发布时间】:2019-03-19 06:50:06
【问题描述】:
我正在使用看起来像这样的 React 组件(我使用的组件的简化版本,如下所示)。
我的问题是:如何制作相同但使用 this.setState? 下面的代码有效,但我直接改变状态,我收到以下警告:
不要直接改变状态。使用 setState()
class App extends Component {
constructor(props) {
super(props);
this.state = {
playerState: [
{
name: 'Jack',
hp: 30
},{
name: 'Alan',
hp: 28
}
],
};
}
lowerPlayerHealth = (index) => () => {
this.state.playerState[index].hp = this.state.playerState[index].hp - 1
this.forceUpdate();
}
render() {
return (
<div className="App">
<p>Player 1: {this.state.playerState[0].name}</p>
<p>Health: {this.state.playerState[0].hp}</p>
<button onClick={this.lowerPlayerHealth(0)}>Hit player 1</button>
<p>Player 2: {this.state.playerState[1].name}</p>
<p>Health: {this.state.playerState[1].hp}</p>
<button onClick={this.lowerPlayerHealth(1)}>Hit player 2</button>
</div>
);
}
}
渲染后是这样的:
【问题讨论】:
-
简单的阅读setState() docs 会让你自己解决这个小问题
-
@charlietfl 我会读一遍
-
如果
this.state.playerState[index]作为 prop 传递给子组件,并且这个子组件是extends PureComponent,它永远不会在更改时重新渲染。这只是第一个用例,当突变状态可以完全破坏您的应用程序中的某些内容时。有一系列原因遵循文档并且从不改变状态。
标签: javascript reactjs stateful