[英]useState: updating array with asyncstorage data
I need to update an array passing some data that I have in my asyncstorage, the problem is the data i send in set don't recive the argument i'm passing and in consequence my state isn't print the data i' m trying to pass我需要更新一个数组,传递我在异步存储中的一些数据,问题是我在集合中发送的数据没有收到我正在传递的参数,因此我的状态没有打印我正在尝试的数据通过
const [carList, setCarList] = useState([]);
const getStorage = async () => {
const newCar = await AsyncStorage.getItem('car');
const car = JSON.parse(newCar)
setCarList([...carList, car]);
console.log(carList);
}
The console.log supose to be like: console.log 应该是这样的:
Array [ Object { "id": 1, "marca": "Alfa Romeo", "modelo": "MiTo", "observaciones": "Color rojo", "placas": "A00-AAA" } ]数组[对象{“id”:1,“marca”:“阿尔法罗密欧”,“modelo”:“MiTo”,“observaciones”:“颜色rojo”,“placas”:“A00-AAA”}]
but the result i have is但我的结果是
Array []大批 []
I recommendo you to use useEffect:我建议您使用 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);
},[]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.