我只想重置某些(不是全部)状态。
单击按钮后,应将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
保存修改后的状态。
答案 0 :(得分:2)
您可以使用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
});
}
答案 1 :(得分:1)
您可以创建一个对象来存储您的状态,您要重置的初始状态,例如:
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按钮上
希望有帮助。 ^^
答案 2 :(得分:1)
在此处使用传播运算符可能会有用。
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
});
}