Car*_*off 1 javascript state reactjs
我真的很难用 React 中的方法将状态重置回原来的状态。我当前的重置方法仅重置该值。我尝试添加等于原始状态的 const,然后将状态设置为等于该状态,但我没有运气。
有什么建议吗?
class App extends Component {
state = {
counters: [
{ id: 1, value: 4 },
{ id: 2, value: 0 },
{ id: 3, value: 0 },
{ id: 4, value: 0 }
]
};
handleReset = () => {
const counters = this.state.counters.map(c => {
c.value = 0;
return c;
});
this.setState({ counters: counters });
};
}
Run Code Online (Sandbox Code Playgroud)
您可以将初始状态保留在单独的数组中,并创建该数组的副本作为初始状态,并且在使用handleReset.
例子
const counters = [
{ id: 1, value: 4 },
{ id: 2, value: 0 },
{ id: 3, value: 0 },
{ id: 4, value: 0 }
];
class App extends React.Component {
state = {
counters: [...counters]
};
handleReset = () => {
this.setState({ counters: [...counters] });
};
handleClick = index => {
this.setState(prevState => {
const counters = [...prevState.counters];
counters[index] = {
...counters[index],
value: counters[index].value + 1
};
return { counters };
});
};
render() {
return (
<div>
{this.state.counters.map((counter, index) => (
<button id={counter.id} onClick={() => this.handleClick(index)}>
{counter.value}
</button>
))}
<div>
<button onClick={this.handleReset}>Reset</button>
</div>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10201 次 |
| 最近记录: |