簡體   English   中英

使用 useEffect 和 asyncstorage 數據更新平面列表

[英]Update a flatlist with useEffect and asyncstorage data

我有兩個屏幕,第一個屏幕(Entry.js)就像一個表單,我在其中輸入了一些數據並將其保存在 asyncstorage 中

const entryVehicleLocal = async ({values}) => {

    const currentDay = new Date();
    const date = String(currentDay);
    const dateSlice = date.slice(4, -15);
    const issuedDate = String(dateSlice);
    values.issuedDate = issuedDate;
            
    const id = shortid.generate();

    const valuesLocal = {
        id: id,
        issuedDate: issuedDate,
        type: values.type,
        color: values.color,
    }

    saveCar(JSON.stringify(valuesLocal));
    
}

const saveCar = async (carJSON) => {
    try {
        await AsyncStorage.setItem('car', carJSON);
        console.log('Logrado');
    } catch (error) {
        console.log(error);
    }
}

然后我有第二個屏幕(Parking.js),我想在平面列表中顯示我保存在異步存儲中的數據,但這是我的問題,我試圖使用 useEffect 自動刷新我的數據,但是當我這樣做時,它只是刷新一次,然后從不更新數據,因此 flatlist 只顯示一個元素,我想要我在第一個屏幕中輸入的所有項目

const [carList, setCarList] = useState([]);

useEffect(() => {
    getStorage();
}, [setCarList]);

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

我希望你可以幫助我

在您的 flatlist 組件中設置 extradata 以在數據更新時重新渲染,

<FlatList ... extraData={carList}/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM