如何在 React Native 中重置状态值?

How to reset the value of a state in React Native?

我想在单击按钮 resetvalues 时将 initialState 中的项目状态重置并保存为 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 来保存修改后的状态。

成功了!

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
}

export default class MarkAttendanceScreen extends Component {

  constructor(props) {
    super(props);
    this.state = {
      ...defaultState,
      refreshing: false,
    }
  }

  resetvalues = () => {
    this.setState({
      ...defaultState,
      subjects: this.state.subjects,
      text: this.state.text
    });
  };
  ...
};