无法访问 React Native 中的 fetch 内部状态

223*_*eca 1 reactjs react-native fetch-api

在 React Native 中,我有以下内容:

import React, { Component }                                         from 'react';
import PropTypes                                                    from 'prop-types';
import { StyleSheet, Text, View, TouchableHighlight }               from 'react-native';
import Immutable                                                    from 'immutable';

const styles = StyleSheet.create({
  map: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: '20%',
  },
});

export default class VirtualFenceBottom extends Component {

  constructor(props) {
    super(props);
    this.state = { markers: this.props.markers  };
  }

  populateMarkers = () => {
    let markersVar = this.state.markers;
    fetch('http://localhost:8080/virtualFence', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }}).then(function(response){
          console.log('GET markers success');

          // Parse it as JSON
          parsedResponse = JSON.parse(response["_bodyInit"]);

          console.log('response after JSON.parse: ',parsedResponse);

          if (parsedResponse.length > 0) {
            //update state here
            console.log('parsedResponse in if statement: ',parsedResponse);
            // this.setState({markers: parsedResponse});
          } else {
            console.log('There were no markers in db');
          }



          console.log('markersVar: ',markersVar);
          // console.log('this.state.markers after setState: ',this.state.markers);

        }).catch(function(error) {
          console.log('GET markers error');
          console.log("GET markers error: ",error);
        });
  };

  render() {

    return (
      <View>
        <TouchableHighlight onPress={this.populateMarkers}>
          <Text style={styles.text}>Populate markers from DB</Text>
        </TouchableHighlight>
      </View>
    );
  }}
Run Code Online (Sandbox Code Playgroud)

一切都按预期进行,除了我无法直接在fetch. 奇怪的是,我可以在包含函数中使用markerVar. 似乎它fetch本身有一个特殊的问题。

我的目标是用响应更新状态。类似问题的现有答案似乎都不适用于我的情况。我该怎么办?

更新 1:添加了整个组件的代码。

更新 2:修复了parsedResponse导致部分错误的变量拼写错误。

Zbi*_*ski 5

响应fetch结果而调用的回调只是取消绑定函数。尝试这个:

}}).then(function(response){
    console.log('this', this); // see that 'this' is not
                               // what you expect it to be
Run Code Online (Sandbox Code Playgroud)

请注意,function() { ...}在 javascript 中创建捕获所有局部变量的闭包(包括您的marketsVar,但包括_this__。

因此,“this”指向没有状态的“window”变量(通常)。

要解决此问题,您可以

1)使用粗箭头函数thencatch处理程序:(我们在 2018 年!,你的工具链肯定会处理它):

fetch(...)
    .then(() => {
         this.setState(...) // this is defined. magic!
Run Code Online (Sandbox Code Playgroud)

2)创建别名this-that有时使用:

var that = this;
fetch(...)
    .then(function() {
         that.setState(...); // that is defined in same way as marketsVar
    })
Run Code Online (Sandbox Code Playgroud)

3)bind手动处理您的处理程序,但这太丑了,所以我不推荐它。