【问题标题】:function returns "undefined" in react.js函数在 react.js 中返回“未定义”
【发布时间】:2020-10-11 12:08:13
【问题描述】:

类中的我的函数在尝试使用返回值时返回 undefined。

App.js:

let db = new Database()
let username = db.get()

return(
  //returns undefined
  <p>{username}</p>
)

database.js:

class Database {
 [...]

 get(){
 [...]
 .then((result) => {
    //console.log logs the right data
    console.log(result.rows[0])
    return (result.rows[0])
  })
 }
}

【问题讨论】:

  • 可能 database.js 什么都不返回,因为 then() 中的 return 不会从 get() 返回。你能展示整个 database.js 吗?
  • 您是从database.js 导入Database 吗?类 Database 是否从 database.js 正确导出?

标签: javascript node.js reactjs npm


【解决方案1】:

如果您希望数据库中的 get() 返回结果,则需要从 Promise 返回解析结果。否则,它只是一个 void 方法。

class Database {
 [...]

 async get(){
 return await [...]
     .then((result) => {
        //console.log logs the right data
        console.log(result.rows[0])
        return (result.rows[0])
      })
   }
}

请注意,在这种情况下 [...] 必须是 promise 对象。通过将方法标记为异步然后等待承诺结果,您可以返回已解决的值而不是未定义的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-22
    • 2019-01-07
    • 2020-10-03
    • 1970-01-01
    相关资源
    最近更新 更多