我想通过单击initialState
按钮将resetvalues
中的项目的状态重置并保存为0。
const initialState = {
present_count: [0, 0, 0, 0, 0, 0, 0],
total_count: [0, 0, 0, 0, 0, 0, 0],
present: 0,
total: 0
};
export default class MarkAttendanceScreen extends Component {
constructor(props) {
super(props);
this.state = {
subjects: [],
text: "",
...initialState,
}
}
resetvalues = () => {
this.setState({ ...initialState });
};
...
};
注意:当前代码未更改并保存这些值的状态。我使用了一个警报框来检查该功能是否可访问,效果很好!我正在使用AsyncStorage保存修改后的状态。
您不应该将initialState放在this.state之外,这是React中生命周期的规则,请尝试这种方式;
export default class MarkAttendanceScreen extends Component {
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
}
}
resetvalues = () => {
const resettedCount = [0, 0, 0, 0, 0, 0, 0]
this.setState({
present_count: resettedCount, total_count: resettedCount,
present: 0, total: 0
});
};
...
};