React Native中的重置组件状态

问题描述 投票:0回答:3

我只想重置某些(不是全部)状态。单击按钮时,应将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保存修改后的状态。

javascript reactjs react-native state reset
3个回答
0
投票

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

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

在您的按钮上的onClick

希望有帮助。 ^^


0
投票

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

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

0
投票

您可以使用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
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.