【问题标题】:useState: updating array with asyncstorage datauseState:使用异步存储数据更新数组
【发布时间】:2020-10-12 18:07:07
【问题描述】:

我需要更新一个数组,传递我在异步存储中的一些数据,问题是我在集合中发送的数据不接收我正在传递的参数,因此我的状态不是打印我的数据我试图通过

    const [carList, setCarList] = useState([]);
        
    const getStorage = async () => {
        const newCar = await AsyncStorage.getItem('car');
        const car = JSON.parse(newCar)
        setCarList([...carList, car]);
        console.log(carList);
    }

console.log 假设如下:

数组 [ 目的 { “身份证”:1, “马卡”:“阿尔法罗密欧”, “模型”:“MiTo”, "observaciones": "Color rojo", “广场”:“A00-AAA” } ]

但我得到的结果是

数组[]

【问题讨论】:

    标签: javascript react-native react-hooks use-state asyncstorage


    【解决方案1】:

    我推荐你使用 useEffect:

    import React, {useState, useEffect} from react;
    
    const [carList, setCarList] = useState([]);
    
    // When the component did mount you will fetch for data and update your state
     useEffect(async ()=>{
        
        const newCar = await AsyncStorage.getItem('car');
        const car = JSON.parse(newCar);
        setCarList([...carList, car]);
        console.log(carList);
    
     },[]);
     
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-02
      • 1970-01-01
      • 2020-02-01
      相关资源
      最近更新 更多