如何在React中使用fetch()API到setState [英] How to use fetch() API in React to setState

查看:453
本文介绍了如何在React中使用fetch()API到setState的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在React中编写一个组件,该组件将使用fetch()API从网站获取数据,然后使用setState设置一个等于该数据的状态,然后最终呈现该数据.我的代码如下:

I'm trying to write a component in React that will use the fetch() API to get data from a website, then use setState to set a state equal to the data, and then finally render the data. My code looks like this:

import React from 'react';

export default class Test extends React.Component {
    constructor(props){
        super(props);
        this.state = {apiInfo: 'default'};
    }

    componentDidMount(){
        fetch('https://fcctop100.herokuapp.com/api/fccusers/top/recent').then(
            function(response){
                return response.json();
            }
            ).then(function(jsonData){
                return JSON.stringify(jsonData);
            }
            ).then(function(jsonStr){
                this.setState({apiInfo: jsonStr});
                console.log(jsonStr);
            });
    }

    render(){
        return(
                <tr>
                    <td>{this.state.apiInfo}</td>
                </tr>
        );
    }
}

但是,这导致出现错误,提示我无法将setState设置为undefined.我最终在HTML上渲染了默认".我在这里到底在做什么错?

However, this results with an error saying I'm unable to setState of undefined. I end up rendering 'default' on my HTML. What exactly am I doing wrong here?

推荐答案

您的错误消息告诉您确切的问题是什么:

Your error message is telling you exactly what the problem is:

无法设置未定义的状态

unable to setState of undefined

因此,您正在尝试调用setState作为当时不存在的对象的方法.作为哪个对象的属性,您试图将setState作为方法调用?

So you're trying call setState as a method of an object that doesn't exist at that point. As a property of what object are you trying to call setState as a method?

this.setState({apiInfo:jsonStr});

this.setState({apiInfo: jsonStr});

是的,这是您的this问题.在您要调用它的时候-即在fetch调用的.then()内部-this实际上是未定义的.您可以在Chrome Devtools中看到这一点:

Yes, it's your this that's the problem. At the point that you're trying to call it - i.e. inside a .then() of a fetch call - this is actually undefined. You can see this in the Chrome Devtools:

恐怕this是JavaScript的客户.它的值可以(并且确实)根据您应用的当前上下文而变化.

I'm afraid that this is a slippery customer in JavaScript; its value can (and does) change depending upon the current context of your app.

有几种方法可以解决此问题.一种稍微笨拙(但可行!)的方法是在输入.fetch()调用之前捕获您的this值,并将其分配给另一个变量.您经常会看到thatself变量用于此目的,但它们只是约定.您可以按自己喜欢的方式调用该变量.

There's several ways you can workaround this. One slightly clunky (but it works!) way is to capture your this value before you enter your .fetch() call, and assign it to another variable. You'll often see that or self variables used for this purpose, but they're just conventions. You can call the variable what you like.

这是我重新处理您的componentDidMount()方法的方法,该方法将this捕获到that,并在.then()内部调用that:

Here's how I've reworked your componentDidMount() method capturing this to that, and calling that inside the .then():

componentDidMount() {
    const that = this;
    fetch("https://fcctop100.herokuapp.com/api/fccusers/top/recent")
        .then(function(response) {
            return response.json();
        })
        .then(function(jsonData) {
            return JSON.stringify(jsonData);
        })
        .then(function(jsonStr) {
            that.setState({ apiInfo: jsonStr });
            console.log(jsonStr);
        });
}

如果您习惯使用箭头函数,那么另一种方法是用一个替换您的常规"函数调用,如下所示:

If you're comfortable using arrow functions, then another way is to replace your "normal" function call with one, like so:

.then(jsonStr => {
    this.setState({ apiInfo: jsonStr });
    console.log(jsonStr);
});

箭头函数的this始终是其父级定义的this.

An arrow function's this is always the this that its parent defined.

这篇关于如何在React中使用fetch()API到setState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆