【问题标题】:ReactJS getting results from a PromiseReactJS 从 Promise 中获取结果
【发布时间】:2021-12-28 14:16:25
【问题描述】:

在我的 sagas 中,我将用户凭据发送到后端

const request = client.post('api/JwtAuth/GenerateToken', {UserName: action.username, Password: action.password})
console.log(request) 

客户端看起来像这样

从“axios”导入axios

const client = axios.create({
    baseURL: 'https://localhost:5001/',
    timeout: 600000000000,
    headers: {
        ContentType: 'application/json'
    }
})

export default client

【问题讨论】:

    标签: javascript reactjs redux-saga


    【解决方案1】:

    你的问题是什么?如果问题是你为什么在控制台上看到 Promise?那是因为你正在处理承诺,要么使用 .then

    client.post().then(res => console.log(res.data)).catch(err => console.log(err))
    

    或异步等待语法

    await client.post()
    

    【讨论】:

    • 我一直使用 await 但我的函数不喜欢它,因为我声明它像 function *fetchUser(action)
    • 呃,比使用 Promise.then() 更适合你的情况
    • 我需要内联做所有事情吗?似乎我在我的 .then() 语句中添加了逻辑,例如从数据中提取值到变量中,然后在数据为空/未定义时管理异常。
    • 不,没有必要。 .then(res => {}) 语句用于处理当/如果承诺被解决时的情况。通常,在前端应用程序中,您使用 res 参数来更新状态或向 UI 呈现新内容。您使用 catch 来处理错误。如果您担心代码的样式,可以在新行上写 .then().catch(),如下所示:dcv19h61vib2d.cloudfront.net/thumbs/…
    【解决方案2】:
      const request = client.post('api/JwtAuth/GenerateToken', {UserName: 
        action.username, Password: action.password})
    
      request.then(response => {
        // the response body can be accessed through the "data" property
        console.log(response.data)
      })
      console.log(request) 
    

    更新:

    你是在传奇中这样做的,对吧? 如果是这样,获取请求响应数据的最佳方法是使用call 效果。从redux-saga/effects 导入,得到如下响应:

      const response = yield call(
        client.post,
        'api/JwtAuth/GenerateToken',
        { UserName: action.username, Password: action.password }
      )
    
      console.log(response.data)
    

    【讨论】:

      猜你喜欢
      • 2019-03-27
      • 2015-07-15
      • 2017-07-22
      • 1970-01-01
      • 2014-03-10
      • 2020-08-01
      • 1970-01-01
      • 2021-01-13
      • 1970-01-01
      相关资源
      最近更新 更多