无法在 React Native 中访问 fetch 中的状态

Cannot access state inside fetch in React Native

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

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

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

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

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

确保此函数存在于组件内部,否则它将无法访问词法作用域的this.state方法。

class MyComp extends React.Component {

  state = { val: 0 }

  myMethod = () => {
    this.setState({ val: 2 })
  }
}

还要考虑从状态中提取值时保持名称一致。例如:

const { markers } = this.state

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

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

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

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

要解决此问题,您可以

1) 使用胖箭头函数 then 并在 catch 处理程序中:(我们在 2018 年!您的工具链肯定会处理它):

fetch(...)
    .then(() => {
         this.setState(...) // this is defined. magic!

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

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

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