【问题标题】:how to increment asyncStorage value on every app launch in react-native?如何在 react-native 中每次启动应用程序时增加 asyncStorage 值?
【发布时间】:2019-01-22 07:12:51
【问题描述】:

每次应用启动时,我都想从 AsyncStorage 增加 myKey 变量。 但就我而言,价值永远不会改变。每次应用启动时我都会得到 1。

任何人都知道如何增加 asyncStorage 的变量。

这是我的代码

 import React, { Component } from 'react';
 import { AsyncStorage, View, Text } from 'react-native';

 export default class App extends Component {
   constructor() {
     super();
     this.state = {
       myKey: 0
      }
    }

  componentWillMount() {
    this.saveData();
 }

 saveData() {
   AsyncStorage.setItem('myKey', this.state.myKey + 1);
   this.setState({'myKey': JSON.parse(this.state.myKey + 1)});
 }

 componentDidMount() {
   AsyncStorage.getItem('myKey').then((value) => {
    this.setState({'myKey': value});
  });
  console.log(this.state.myKey);
}

render() {
   return (
      <View>
        <Text>Hello World</Text>
     </View>
    );
  }
}

【问题讨论】:

    标签: react-native increment launch asyncstorage


    【解决方案1】:

    ComponentWillMount 在 ComponentDidMount 之前触发,因此您始终将密钥设置为 1(因为您的 state.key = 0),然后您获取存储密钥并将状态更新为 1。此外,您只能将字符串值保存在 AsyncStorage , 所以你必须先从 string 到 int 进行转换,以便进行计算,然后从 int 到 string 才能保存值。 我会这样做:

    async componentDidMount() {
        let key = parseInt(await AsyncStorage.getItem('myKey'));
        AsyncStorage.setItem('myKey', (key + 1).toString());
    });
    

    【讨论】:

      【解决方案2】:

      看起来你的逻辑有问题。目前,在增量逻辑(在 componentDidMount() 中)之前调用持久逻辑(在 componentWillMount() 中)。

      这意味着;

      1. 您的组件触发componentWillMount(),它通过AsyncStorage.setItem()0 的值(取自初始状态)保存到键myKey
      2. 接着,下一个生命周期钩子; componentDidMount() 被解雇。在这里,您通过AsyncStorage.getItem()(设置为0)加载myKey 的值并将其增加到1

      要解决此问题,请考虑修改您的组件,以便加载、递增和持久化 myKey 值的逻辑包含在 componentDidMount() 生命周期挂钩中,如下面的代码和 cmets 中所述:

       export default class App extends Component {
         constructor() {
           super();
           this.state = {
             myKey: 0
            }
          }
      
       componentDidMount() {
      
         AsyncStorage.getItem('myKey').then((value) => {
      
          // Parse value which is a string to number so 
          // that arithmetic can be performed in a safe
          // and predictable way
          value = parseInt(value);
      
          // If invalid parse result, default first value
          // to zero
          if(isNaN(value)) {
             value = 0;
          }
      
          // Update state
          this.setState({'myKey': value});
      
          // Add this to persist the incremented value for 
          // use on next launch. Format value as string with
          // "back ticks"
          AsyncStorage.setItem('myKey', `${value}`);
        });
      }
      
      render() {
         return (
            <View>
              <Text>Hello World</Text>
              <Text>${ this.state.myKey }</Text>
           </View>
          );
        }
      }
      

      【讨论】:

        【解决方案3】:

        你有没有像下面这样尝试过。

        componentDidMount() {
           AsyncStorage.getItem('myKey').then((err, value) => {
            if (isNaN(err)) {
              if(isNaN(value)) {
                value = 0;
              } else {
                value = parseInt(value);
              }
              AsyncStorage.setItem('myKey', value + 1);
            }
          });
        }
        

        Error 是第一个参数不是value 请检查here

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-02-28
          • 1970-01-01
          • 1970-01-01
          • 2021-09-09
          • 1970-01-01
          相关资源
          最近更新 更多