React - 未设置组件状态

问题描述 投票:2回答:3

为什么这段代码的输出低于“真”?

class InstagramGallery extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            images: true
        };
    }

    componentDidMount() {
        var accessToken = '*Instagram token*';
        var instagramApi = new Instagram(accessToken);
        instagramApi.userSelfMedia().then(function(result) {
            this.setState({
                images: false,
            });
        }, function(err) {
            console.log(err);
        });

    }

    render() {
        console.log(this.state.images); 
        return (
            <div className="instagram-gallery">

            </div>
        )
    }
}

据我所知,首先调用构造函数。因此images=true,然后用console.log(true)渲染,并且componentDidMount被称为。在获取来自instagram的数据后,我更新组件状态,该组件状态应该使用images=false重新渲染组件。我哪里错了?

javascript reactjs web
3个回答
4
投票

您正在使用常规函数进行instagramAp.userSelfMedia回调,从而失去this上下文。使用箭头功能代替:

instagramApi.userSelfMedia().then(
  result => {
    this.setState({
      images: false
    });
  },
  function(err) {
    console.log(err);
  }
);

常规函数创建自己的词法范围,因此this不会将您的类指向回调函数。箭头函数不会创建自己的词法范围,this指向您的组件,您可以使用this.setState()

使用箭头功能可以避免绑定函数或将this保存在另一个变量中,如:

var accessToken = "*Instagram token*";
var instagramApi = new Instagram(accessToken);
const that = this;
instagramApi.userSelfMedia().then(
  function(result) {
    that.setState({
      images: false
    });
  },
  function(err) {
    console.log(err);
  }
);

2
投票

我这么长时间没有使用RN,但这有影响吗?

componentDidMount() {
    var accessToken = '*Instagram token*';
    var instagramApi = new Instagram(accessToken);
    instagramApi.userSelfMedia().then((result) => { //USING ARROW FUNCTION
        this.setState({
            images: false,
        });
    }, function(err) {
        console.log(err);
    });

}

我添加了一个箭头函数,以便'this.state'不会与instagramApi.userSelfMedia()中的'this'混淆。


2
投票

因为这不可用

使用箭头功能

 instagramApi.userSelfMedia().then((result) => {
        this.setState({
            images: false,
        });
    }, function(err) {
        console.log(err);
    });

  }

或者手动绑定它

  instagramApi.userSelfMedia().then(function(result) {
        this.setState({
            images: false,
        });
    }.bind(this), function(err) {
        console.log(err);
    });

  }
© www.soinside.com 2019 - 2024. All rights reserved.