调用setState()时,FETCH帮助器函数返回未定义的

时间:2020-06-03 21:14:27

标签: javascript reactjs fetch state setstate

我有一个辅助函数,该函数使用FETCH从API中提取数据。我正在尝试使用setState()将获取请求的响应设置为我的状态,但是它一直返回未定义状态。这是我的辅助函数:(我意识到我将密钥暴露在前端,但是如果我部署到生产环境,我会进行调整)

const authCode = {
    async getAuthCode() {
        const authCodeMatch = window.location.href.match(/code=([^&]*)/)[1];
        await fetch(`https://id.twitch.tv/oauth2/token?client_id=${TWITCH_ID}&client_secret=${TWITCH_SECRET}&code=${authCodeMatch}&grant_type=authorization_code&redirect_uri=${TWITCH_CB}`, {
            method: 'POST',
            mode: 'cors',
            'Access-Control-Allow-Origin':'*',
            credentials: 'same-origin', 
            headers: {
             'Content-Type': 'application/json'
            }
        })
        .then(response => 
            response.json()    
        )
        .then(data => {
            console.log(data.access_token);
            fetch(`https://api.twitch.tv/helix/users?id=43691`, {
                method: 'GET',
                mode: 'cors',
                'Access-Control-Allow-Origin':'*',
                credentials: 'same-origin',
                headers: {
                    'Content-Type': 'application/json',
                    'Client-ID': TWITCH_ID,
                    'Authorization': 'Bearer ' + data.access_token
                }
            })
            .then(response => response.json())
            .then(newdata => {
                console.log(newdata);
                if (!newdata.data) {
                    return [];
                }
                //console.log(newdata.data[0].view_count);
                return newdata.data.map(views => ({
                    view_count: views.view_count
                }))
            })
        })
    }

一切都很好地记录到控制台,所以我很确定我正在映射通过正确的数组来解析数据。无论如何,这是控制台中返回的对象以及我的组件代码。在我的个人资料组件中,它只是将undefined推到我的状态:

// Console response
data: Array(1)
0:
broadcaster_type: "partner"
description: ""
display_name: "Faker"
id: "43691"
login: "faker"
offline_image_url: "https://static-cdn.jtvnw.net/jtv_user_pictures/7d76e34d-3ee3-42c0-a46b-e320d37fcde6-channel_offline_image-1920x1080.jpeg"
profile_image_url: "https://static-cdn.jtvnw.net/jtv_user_pictures/b2eb8a23-d6ad-45aa-bd8e-062133b64452-profile_image-300x300.png"
type: ""
view_count: 81769581
__proto__: Object
length: 1
__proto__: Array(0)

组件

export default class Profile extends Component {

    constructor(props) {
        super(props);

        this.state = {
            viewData: []
        }

        this.handleNewPost = this.handleNewPost.bind(this);

    }

    handleNewPost () {
        authCode.getAuthCode().then(viewcountResults => {
            this.setState({viewData: viewcountResults})
        })
    }

    render() {
        return (
            <div>
                <Container>
                <div className='mt-5'>
                <Button color='success' size='lg' onClick={this.handleNewPost}>
                    Post Data
                </Button>
                </div>
                <div>
                {this.state.viewData.view_count}
                </div>
                </Container>
            </div>
        )
    }

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您的函数mysetup.exe /PORT=1337未返回包含您要接收的数据的Promise。另外,您可以使用getAuthCode而不是await和回调的混合来大大清理该代码。

await
相关问题