在 React Native 中重置组件状态

Reset component state in React Native

我只想重置某些(不是全部)状态。 单击按钮时,present_counttotal_countpresenttotal 的值应设置为其初始状态 (0)。而 subjectstext 的状态应该保持不变。

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 来保存修改后的状态。

您可以创建一个对象来存储您的状态您想要重置的状态的初始状态,如下所示:

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

点击您的按钮

希望有所帮助。 ^^

在这里使用展开运算符可能会有用。

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

您可以使用 spread operator 覆盖当前状态值,然后使用 textsubjects:

的当前状态值
// 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
  });
}