【问题标题】:Add object to array and save the array to async storage react native将对象添加到数组并将数组保存到异步存储反应本机
【发布时间】:2021-08-27 09:00:15
【问题描述】:

我正在下载一些文件并将它们的数据保存到本地存储以进行本机反应。下载工作正常,但我试图将对象数据保存到数组并将数组存储在本地存储中。当我试图保存该项目时,问题就出现了。我必须单击两次下载按钮来保存项目,否则数组在本地存储中保持为空并且不会更新。

const [value, setValue] = useState(0);
const [initialElements, setinitialElements] = useState([]);
const [videoid, setvideoid] = useState(0);
      
//Downloading Video file
const downloadVideo = async () => {
    RNFetchBlob.config({
        fileCache: true,
        appendExt: 'mp4',
    }).fetch(
        'GET',
        'https://cdn.videvo.net/videvo_files/video/premium/getty_105/large_watermarked/istock-1083459308_preview'
    ).progress((received, total) => setValue(Math.round((received / total) * 100)).then(res => {
        setvideopath(res.path());
        console.log('Video Complete');
        addElement();
    });
};

const addElement = async () => {
    let ItemData = {
        itemKey: videoid,
        itemName: 'Object ' + (videoid+ 1),
        image: imgpath,
        video: videopath,
    };
      
    //Pushing new object into array

    var newArray = [...initialElements, ItemData];
    setvideoid(videoid+ 1);
    setinitialElements(newArray);
    try {
        await AsyncStorage.setItem('cachedvideos', JSON.stringify(initialElements));
    } catch (error) {
        // Error saving data
    }
};
    
return (
    <View>
        <Button title="Download" onPress={downloadVideo}/>
        <View style={{
          alignItems: 'center',
          marginTop: 25,
        }}>
            <AnimatedCircularProgress
                size={25}
                width={4}
                fill={value}
                tintColor="#00e0ff"
                backgroundColor="#3d5875"
            />
        </View>
    </View>
);

我只需要使用要在另一个屏幕中使用的新对象来更新本地存储上的数组。

【问题讨论】:

    标签: reactjs react-native caching react-hooks


    【解决方案1】:

    我相信这是由于您的代码中的一个小错误:

    var newArray = [...initialElements, ItemData];
    setvideoid(videoid+ 1);
    setinitialElements(newArray);
    try {
      await AsyncStorage.setItem(
        'cachedvideos',
        JSON.stringify(initialElements), <-- change to newArray
      );
    } catch (error) {
       // Error saving data
    }
    

    您正在将initialElements 保存到本地存储中,这是以前的值,而不是更新后的值。这就是为什么您需要下载视频两次:第二次initialElements 将等于上一次下载期间的newArray

    我还建议您更新 itemName 字段:

    const addElement = async () => {
    let ItemData = {
    itemKey: videoid,
    itemName: 'Object ' + (videoid+ 1), <-- remove the + 1
    image: imgpath,
    video: videopath,
    };
    

    否则itemName 将指示此特定项目对应于键videoid + 1,但事实并非如此。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-28
      • 2023-03-08
      • 2020-04-20
      • 2020-06-13
      • 1970-01-01
      • 2012-12-11
      • 1970-01-01
      • 2020-12-03
      相关资源
      最近更新 更多