【问题标题】:Problem to return a fetch in the async function | Part 2在异步函数中返回 fetch 的问题 |第2部分
【发布时间】:2021-02-03 17:26:03
【问题描述】:

我目前遇到一个问题,我希望能够返回 fetch 接收到的内容,例如:

{"data": [{"account_id": 134519399, "account_url": "Pseudo", "ad_type": 0, "ad_url": "", "animated": false, "bandwidth": 110238, "datetime": 1603190775, "deletehash": "Mg3FROsdfPF7N", "description": null, "edited": "0", "favorite": false, "has_sound": false, "height": 368, "id": "3HzN2Ye", "in_gallery": false, "in_most_viral": false, "is_ad": false, "link": "https://i.imgur.com/lbWS8uo.jpg", "name": "unnamed.jpg", "nsfw": null, "section": null, "size": 55119, "tags": [Array], "title": null, "type": "image/jpeg", "views": 2, "vote": null, "width": 512}], "status": 200, "success": true}

但我目前正在收到这个:

{"_U": 0, "_V": 0, "_W": null, "_X": null}

这是我的代码:

export default async function FetchImage(access_token) {
var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer " + access_token);

var formdata = new FormData();

var requestOptions = {
    method: 'GET',
    headers: myHeaders,
    redirect: 'follow'
};

try {
    const response = await fetch("https://api.imgur.com/3/account/me/images", requestOptions)
    // console.log(await response.text());
    return response.json
}
catch (err) {
    console.log('fetch failed', err);
}
}

我在这个类中调用我的函数:

var ress;
    export default class ImageNav extends Component {
    constructor(props) {
        super(props);
    }
 
    _getAccessToken() {
        var res = this.props.navigation.state.params.access_token;
        return res
    }
 
    render() {
        // console.log(this._getAccessToken())
        ress = FetchImage(this.props.navigation.state.params.access_token)
        console.log(ress)
        return (
            <>
                <View>
                    <Text>access_token: {this._getAccessToken()}</Text>
                </View>
                <View style={styles.buttonFav}>
                    <Button buttonStyle={{ backgroundColor: '#4D4D4D' }} title="FavNav" onPress={() => this.props.navigation.navigate('FavNav')}></Button>
                </View>
                <View style={styles.buttonFind}>
                    <Button buttonStyle={{ backgroundColor: '#4D4D4D' }} title="FindNav" onPress={() => this.props.navigation.navigate('FindNav')}></Button>
                </View>
            </>
        )
    }
}

我查看了这些解决方案:

How do I return the response from an asynchronous call?

async/await implicitly returns promise?

但我还是不能解决我的问题,

如果有人可以帮助我

谢谢!

【问题讨论】:

    标签: javascript react-native api fetch


    【解决方案1】:

    response.json() 也是Promise。所以你应该在它前面附加await

    export default async function FetchImage(access_token) {
    var myHeaders = new Headers();
    myHeaders.append("Authorization", "Bearer " + access_token);
    myHeaders.append("Content-Type", "application/json");
    
    var formdata = new FormData();
    
    var requestOptions = {
        method: 'GET',
        headers: myHeaders,
        redirect: 'follow'
    };
    
    try {
        const response = await fetch("https://api.imgur.com/3/account/me/images", requestOptions)
        // console.log(await response.text());
        return await response.json()
    }
    catch (err) {
        console.log('fetch failed', err);
    }
    }
    

    【讨论】:

    • 您好,感谢您的回答,我在 'response.json()' 前面添加了 'await' 但我还有问题。
    • 尝试将'Content-Type': 'application/json' 添加到您的请求标头中。
    • 好吧,我改了,但什么也没做。当我放console.log(response)时,我有很好的结果但是当我返回时,它不起作用。
    • 好的,非常感谢,我成功了我明天放解决方案
    • @HugoTek,你会发布你找到的解决方案吗?
    【解决方案2】:

    好的@Prime,我刚刚看到,我的解决方案之后会产生同样的问题

     async _getData() {
        try {
            this.state.test = await FetchImage(this.props.navigation.state.params.access_token);
            console.log(this.state.test.data[0]["link"])
            return (this.state.test)
    
        } catch (error) {
            console.error(error);
        }
        // console.log(res)
    
    }
    

    我在这里给他打电话:

    render() {
            try {
                console.log(this._getData())
                
            } catch (error) {
                console.error(error);
            }
            console.log("ici = " + this.props.test)
            return (
                <>
                    <View>
                        <Text>access_token:</Text>
                    </View>
                    <View style={styles.buttonFav}>
                        <Button buttonStyle={{ backgroundColor: '#4D4D4D' }} title="FavNav" onPress={() => this.props.navigation.navigate('FavNav')}></Button>
                    </View>
                    <View style={styles.buttonFind}>
                        <Button buttonStyle={{ backgroundColor: '#4D4D4D' }} title="FindNav" onPress={() => this.props.navigation.navigate('FindNav')}></Button>
                    </View>
                </>
            )
        }
    }

    但是,当我尝试使用存储在“this.state.test”中的内容时,它是“未定义的”。

    console.log(this._getData()) 显示此{"_U": 0, "_V": 0, "_W": null, "_X": null}

    我很绝望:'(

    【讨论】:

      【解决方案3】:

      好的,我找到了解决方案,我必须为收到的内容制作一个setState

      async componentDidMount() {
              try {
                  let res = await FetchImage(this.props.navigation.state.params.access_token);
                  this.setState({ test: res })
              } catch (error) {
                  console.error(error);
              }
          }

      我把它放在componentDidMount() 函数中,这样setState 就不会循环了。

      谢谢大家,非常感谢@Prime。

      【讨论】:

        猜你喜欢
        • 2019-10-08
        • 2013-03-28
        • 2012-07-31
        • 2016-07-17
        • 2014-05-27
        • 1970-01-01
        • 1970-01-01
        • 2021-02-23
        • 2023-04-04
        相关资源
        最近更新 更多