簡體   English   中英

無法從另一個文件 React Native 獲取數據返回

[英]Can't get data return from another file React Native

我正在使用外部實用程序文件。 這只是一個JS文件。

export const getUser = async () =>  {

db = SQLite.openDatabase("PegaPreco_data_src");
await db.transaction(tx => {
    tx.executeSql(
        "create table if not exists user (id text primary key not null, cpf text, nome text, " +
        "email text, senha text);"
    );
});

return await db.transaction(tx => {
    tx.executeSql("select * from user", [],
        (_, { rows }) => {
            console.log('My rowa', rows._array[0]); //console print - Ok
            return rows._array[0];
        },
        (error) => {
            console.error('Data errors \n', error);
        })
})
}

在我完整的 state 組件中,我已經導入了 de 實用程序文件,我正在嘗試獲取數據:

componentDidMount() {
  getUser()
        .then((MyUser) => {
            console.log(MyUser); //undefined here
            this.setState({ user: MyUser });
        })
        .then(console.log('My console.log for tests', this.state.user)); always the user is undefined
...more code...

我無法意識到出了什么問題。 初始 state 是好的

我不熟悉您正在使用的庫,但它看起來像調用db.transaction然后tx.executeSql不返回任何內容,即它不是解析/拒絕具有某些值的Promise 看起來它是基於回調的,因此您必須“手動”執行此操作並將其轉換為Promise

這是一個可能的解決方法:

 // mock for the `db` library you're using const mockDb = { transaction: callback => { callback({ executeSql: (arg1, arg2, cb) => { const user = { id: 1, name: "John Doe", age: 20 }; cb(null, user); } }); } }; // utils/getUser.js const getUser = () => { return new Promise((resolve, reject) => { const db = mockDb; db.transaction(tx => { tx.executeSql("...", "...", () => {}); }); db.transaction(tx => { tx.executeSql("...", [], (_, result) => { resolve(result); }); }); }); } // components/MyComponent.js getUser().then(result => { console.log('result', result); }).catch(error => { console.error(error); })

希望這可以幫助。

因為你實際上需要從 getUser() 中返回數據。 您可以使用 promise 解決拒絕

謝謝你們。 我重構了我的代碼,我意識到這種方式是有效的

export const getUser = async () => {
db = SQLite.openDatabase("PegaPreco_data_src");
return new Promise((resolve, rejected) => {

    db.transaction(tx => {
        tx.executeSql("select * from user", [], (_, { rows }) => {
            resolve(rows._array[0]);
        });
    });
})
}

暫無
暫無

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

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