【问题标题】:How to reset the value of a state in React Native?如何重置 React Native 中的状态值?
【发布时间】:2020-06-14 16:28:23
【问题描述】:

我想通过单击按钮resetvaluesinitialState 中的项目的状态重置并保存为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 来保存修改后的状态。

【问题讨论】:

  • 请尝试this.setState(initialState);
  • 试过了。什么都没做。

标签: javascript reactjs react-native state reset


【解决方案1】:

搞定了!

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-12
    • 1970-01-01
    • 2023-01-16
    • 1970-01-01
    • 2021-02-22
    相关资源
    最近更新 更多