在 React 组件中使用异步函数、等待和解析

Using async function, await and resolve in React component

我有一个具有以下结构的组件:

const _dbCall = () => {
    const fooDb = SQLite.openDatabase(db);
    return new Promise(resolve => {
        fooDb.transaction(tx => {
            tx.executeSql(`SOME SQL`, [], (tx, results) => {
                resolve(results.rows._array);
            }, null);
        });
    })
}

async function _renderSomething() {
    const results = await _dbCall();
    
    return <FlatList
        data={results}
        renderItem={_renderFunc}
        keyExtractor={item => item} />
}

我在Componentrender()函数中使用了_renderSomething()。 然而,这给了我:

Error: Objects are not valid as a React child (found: object with keys {_U, _V, _W, _X}). If you meant to render a collection of children, use an array instead.

这个{_U, _V, _W, _X}对我来说看起来像是一个悬而未决的承诺。 当我从 renderSomething() 中删除 async 关键字时,注释 const results = ... 并将一些虚拟数据传递给 <FlatList ...,它呈现没有问题。

为什么 renderSomething() 不是 return <FlatList ... 而是一个悬而未决的承诺?

您可以在 useEffect 挂钩中使用。

function _renderSomething() {
const [data,setData] =  React.useState([])
  React.useEffect(()=>{ 
(async () => {
    const results = await _dbCall();
    setData(results);
  })()
}, []);
    
    return <FlatList
        data={data}
        renderItem={_renderFunc}
        keyExtractor={item => item} />
}

正如@Yousaf 指出的那样:

const [resultsFromDb, setResultsFromDb] = useState([]);

const _dbCall = () => {
    const foo = [];
    const fooDb = SQLite.openDatabase(db);
    fooDb.transaction(tx => {
        tx.executeSql(`SOME SQL`, [], (tx, results) => {
            // do something the results
            for (let i = 0; i < results.rows.length; i++) {
                foo.push(results.rows.item(i));
            }
            setResultsFromDb(foo)
        }, null);
    });
}

const _renderSomething = () => {
    const results = _dbCall();
    
    return <FlatList
        data={resultsFromDb}
        renderItem={_renderFunc}
        keyExtractor={item => item} />
}