我只想重置某些(不是全部)状态。单击按钮时,应将present_count
,total_count
,present
和total
的值设置为其初始状态(0)。 subjects
和text
的状态应保持不变。
constructor(props) {
super(props);
this.state = {
subjects: [],
text: "",
present_count: [0, 0, 0, 0, 0, 0, 0],
total_count: [0, 0, 0, 0, 0, 0, 0],
present: 0,
total: 0
}
}
编辑:我正在使用AsyncStorage
保存修改后的状态。
您可以创建一个对象来存储您要重置的状态的初始状态,如下所示:
const initState = {
total: 0,
present: 0,
present_count: [0, 0, 0, 0, 0, 0, 0],
total_count: [0, 0, 0, 0, 0, 0, 0],
}
然后您可以
this.setState({
...initialState
})
在您的按钮上的onClick
希望有帮助。 ^^
在这里使用扩展运算符可能会有用。
constructor(props) {
super(props);
this.defaultState = {
present_count: [0, 0, 0, 0, 0, 0, 0],
total_count: [0, 0, 0, 0, 0, 0, 0],
present: 0,
total: 0
}
this.state = {
subjects: [],
text: "",
...defaultState,
}
}
.
.
.
onClick = () => {
this.setState({
...this.defaultState, // This will only pass in values from your defaultState and leave the others (subjects & text) alone
});
}
您可以使用spread operator覆盖当前状态值,然后使用text
,subjects
的当前状态值:
// default state
const defaultState = {
subjects: [],
text: "",
present_count: [0, 0, 0, 0, 0, 0, 0],
total_count: [0, 0, 0, 0, 0, 0, 0],
present: 0,
total: 0
}
// component constructor.
constructor(props) {
super(props);
this.state = defaultState;
}
// click event handler
handleClick = () => {
this.setState({
...defaultState,
subjects: this.state.subjects,
text: this.state.text
});
}