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

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

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

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

您不应该将initialState放在this.state之外,这是React中生命周期的规则,请尝试这种方式;

export default class MarkAttendanceScreen extends Component {
  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
    }
  }

  resetvalues = () => {
    const resettedCount = [0, 0, 0, 0, 0, 0, 0]
    this.setState({  
       present_count: resettedCount, total_count: resettedCount,
       present: 0, total: 0
    });
  };
 ...
};
© www.soinside.com 2019 - 2024. All rights reserved.