简体   繁体   English

通过在React Native中获取来从请求api获取状态和数据

[英]Get status and data from request api by fetch in react native

I try extract data and status request from request in react native, when utilize this code 当使用此代码时,我尝试从响应本机中的请求中提取数据和状态请求

function postUser(FirstName, LastName, Phone, Email, Password) {
    let data = {
        method: 'POST',
        credentials: 'same-origin',
        mode: 'same-origin',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            email: Email,
            password: Password,
            first_name: FirstName,
            last_name: LastName,
            phone: Phone
        })
    }
    return fetch(URLPostUser, data)
        .then(response => response.json())
} 

in this result don't had status. 在此结果中没有状态。

when change the return of function, i try get status, but in this case don't have access to data 当更改函数的返回值时,我尝试获取状态,但是在这种情况下,无法访问数据

function postUser(FirstName, LastName, Phone, Email, Password) {
    let data = {
        method: 'POST',
        credentials: 'same-origin',
        mode: 'same-origin',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            email: Email,
            password: Password,
            first_name: FirstName,
            last_name: LastName,
            phone: Phone
        })
    }
    return fetch(URLPostUser, data)
}

You can do the following 您可以执行以下操作

return fetch(URLPostUser, data)
    .then(response => ({ response, json: response.json()}))

Now the promised object is 现在承诺的对象是

{
    response: // the response object
    json: // the parsed JSON
}

Or if you don't want the whole response 或者,如果您不希望整体回应

return fetch(URLPostUser, data)
    .then(response => ({ status: response.status, json: response.json()}))

The resulting promise is of the object 最终的承诺是对象

{
    status: // the response object
    json: // the parsed JSON
}

https://stackoverflow.com/a/39339648/8533250 https://stackoverflow.com/a/39339648/8533250

Those link was helpful for me. 这些链接对我很有帮助。 Because previously answer return 因为以前的答案返回

{ status: 200, json: Promise})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM