简体   繁体   中英

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

I want to reset and save the state of the items inside initialState to 0 on the click of the button resetvalues .

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 });
  };

 ...

};

NOTE: The current code is not changing and saving the state of those values. I used an alert box to check if the function is accessible, that is working fine. I am using AsyncStorage to save the modified state.

Got it working!

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
    });
  };
  ...
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM