我想将indexedDB中的数据显示到视图中,我使用reactjs

2exbekwf  于 2022-12-09  发布在  IndexedDB
关注(0)|答案(1)|浏览(152)

我想使用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;

有人能帮助我吗,om对不起我的代码结构:(

hs1ihplo

hs1ihplo1#

您应该使用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;

相关问题