【发布时间】:2020-10-25 18:24:55
【问题描述】:
我有一个应用于 4 个不同对象的投票状态,但我的问题是重置方法是否正确,或者我是否应该折射我的 initialState 对象,所以我不需要在重置方法中重复自己。每个对象的增量器和重置按钮在调用时起作用。
类函数扩展 React.Component {
static initialState = {
waves : [
{id: 'Pipeline', votes: 0},
{id: 'Backdoor', votes: 0},
{id: 'Froggies', votes: 0},
{id: 'Waimea', votes: 0}
]
}
constructor(props){
super(props);
this.state = Functions.initialState;
}
reset(e) {
if (e) e.preventDefault();
this.setState({
waves : [
{id: 'Pipeline', votes: 0},
{id: 'Backdoor', votes: 0},
{id: 'Froggies', votes: 0},
{id: 'Waimea', votes: 0}
]
});
}
add (i) {
let oldWaves = [...this.state.waves]
oldWaves[i].votes++
this.setState({waves: oldWaves})
}
render() {
return (
<div className='waves'>
<h1>Vote for your favorite wave!</h1>
{this.state.waves.map((wave, i) =>
<div key={i} className='wave'>
<div className='voteCount'>
{wave.votes}
</div>
<div className='waveDetails'>
{wave.id}
<button onClick={this.add.bind(this, i)}>X</button>
</div>
</div>
)}
<button onClick={this.reset.bind(this)} className='resetButton'>Reset </button>
</div>
)
}
}
【问题讨论】:
-
这个问题的答案太多了。搜索工作。这回答了你的问题了吗? Which of these strategies is the best way to reset a component's state when the props change
标签: javascript reactjs react-state