【问题标题】:This.state undefine after fetch()this.state 在 fetch() 之后未定义
【发布时间】:2017-12-19 16:28:58
【问题描述】:

我有一个问题,在我使用 fetch 之后,我的 this.state 是未定义的,我不明白为什么......

googlePOI(center) {
        this.setState({markerPOI: []});
        var i = 0;
        let call = '';
        call = call.concat(URL_POI, center.lat.toString(), ',', center.lng.toString(), ARG_POI, this.state.filters[i], KEY);
        console.log(this.state) // DEFINE !
        fetch(call)
            .then((answer) => answer.json())
            .then(function(answer) {
                console.log(this.state) // UNDEFINE !
                answer.results.map((item, index) => {
                    let geo = item.geometry.location;
                    let marker = <MapView.Marker title={item.name} coordinate={{latitude: geo.lat, longitude: geo.lng}} />
                })
            }).catch(function(error) {
                console.log("ERROR: fetch googlePOI -> "+error);
            })

    }

【问题讨论】:

  • 一方面,您永远不会使用this.setState({ someState: someValue }) 从获取中更新您的状态。其次,如果this.state 完全未定义,您应该为组件的其余部分提供代码,当然是您的构造函数。

标签: react-native fetch state


【解决方案1】:

这是因为当调用 promise 的回调时,函数的内部上下文发生了变化。换句话说,this 不再是以前的样子了!你可以做一个console.log(this),你会发现自己。

最简单的解决方案是在顶部保留this 的引用:

var me = this;

fetch(url).then(function() {
  console.log(me.state)
});

您也可以将 this 与回调函数绑定:

fetch(url).then(function() {
  console.log(this.state)
}.bind(this));

或者最推荐的 ES2015 Arrows 使用方式:

fetch(url).then(() => {
  console.log(this.state)
});

出于教育目的,我建议写一篇类似what is this的文章

【讨论】:

  • 在 react native 中,这对我不起作用:(。在我的 fetch 响应中,我的 'const t = this' 在我的 fetch 的 then() 语句中是未定义的。我在做什么错了吗?
猜你喜欢
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-24
  • 2018-05-09
  • 2016-07-28
  • 1970-01-01
相关资源
最近更新 更多