Javascript React-未设置组件状态

Javascript React-未设置组件状态,javascript,reactjs,web,Javascript,Reactjs,Web,为什么代码的输出低于“true” InstagramGallery类扩展了React.Component{ 建造师(道具){ 超级(道具); 此.state={ 图像:真的 }; } componentDidMount(){ var accessToken='*Instagram令牌*'; var instagramApi=新Instagram(accessToken); instagramApi.userSelfMedia().then(函数(结果){ 这是我的国家({ 图像:假, }); }

为什么代码的输出低于“true”

InstagramGallery类扩展了React.Component{ 建造师(道具){ 超级(道具); 此.state={ 图像:真的 }; } componentDidMount(){ var accessToken='*Instagram令牌*'; var instagramApi=新Instagram(accessToken); instagramApi.userSelfMedia().then(函数(结果){ 这是我的国家({ 图像:假, }); },函数(err){ 控制台日志(err); }); } render(){ log(this.state.images); 返回( ) } }
据我所知,构造函数是首先被调用的。因此,
images=true
,然后用
console.log(true)
呈现,并调用
componentDidMount
。从instagram获取数据后,我更新组件状态,该状态应使用
images=false
重新呈现组件。我错在哪里?

我已经很久没有使用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”混淆。

您正在为
instagramAp.userSelfMedia
回调使用一个常规函数,因此会丢失
this
上下文。改用箭头函数:

instagramApi.userSelfMedia().then(
  result => {
    this.setState({
      images: false
    });
  },
  function(err) {
    console.log(err);
  }
);
常规函数创建它们自己的词法作用域,因此
不会将类指向回调函数。箭头函数不创建自己的词法范围,以
指向您的组件,您可以使用
此.setState()

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

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);
  }
);

因为这个不可用

使用箭头功能

 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);
    });

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

  }