【问题标题】:i want to show data from indexedDB to the view, im using reactjs我想将 indexedDB 中的数据显示到视图中,我正在使用 reactjs
【发布时间】:2021-04-21 23:45:36
【问题描述】:

我想使用 Reactjs 从 indexdedDB 中检索数据,但我不知道如何将其返回到视图中,

这是我的代码........

import React, { useState, useEffect } from 'react';



function Mypokemon() {
    var db;
    var request = window.indexedDB.open("pokemon_data", 1);
    //on error opening DB
    request.onerror = function (event) {
        console.log("error: ");
    };

    //on success opening DB
    request.onsuccess = function (event) {
        db = request.result;
        console.log("connected to DB")

        db.transaction(['data'], 'readwrite').objectStore('data').openCursor().onsuccess = function (event) {
            var cursor = event.target.result
            if (cursor) {
                //something to do here for applying data to html
            };


        }
    }
    //this code below for make the empty table
    request.onupgradeneeded = function (event) {
        var db = event.target.result;
        var objectStore = db.createObjectStore("data", {
            keyPath: "id"
        });
        console.log('success make table')
    }

    return (<div className="flexin" id="my_poke">
        {/* this where the data should showning */}
    </div >)

}
export default Mypokemon;

谁能帮帮我,对不起我的代码结构:(

【问题讨论】:

    标签: javascript reactjs indexeddb


    【解决方案1】:

    您应该使用useStateuseEffect

    例如:

    import React, { useState, useEffect } from 'react';
    
    function Mypokemon() {
        const [ value, setValue ] = useState();
    
        useEffect(function(){
            const valueFromDb = getValueFromDb();  // make your request
            setValue( valueFromDb );
        },[]);
    
        return (<div className="flexin" id="my_poke">
            { value }
        </div >)
    
    }
    export default Mypokemon;
    

    【讨论】:

    • 我试过这个,但每当我在获得 setValue 后尝试 console.log(value) 时,它什么都不返回......而且只有当我重新加载页面时才会返回。
    猜你喜欢
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 2021-12-22
    • 2015-09-22
    • 1970-01-01
    • 2019-02-14
    • 2018-03-22
    • 1970-01-01
    相关资源
    最近更新 更多