首页 > 解决方案 > undefined 不是函数(评估 'this.setstate(

问题描述

我是本机初学者。我已经使用“axios”npm 包为 API 中的 fech 数据编写了代码。当我运行时运行正常,但是当它获取数据时会抛出错误。

undefined 不是函数(评估 'this.setstate(

我怀疑这个绑定有问题,但我不知道如何修复它。请帮我解决这个错误。

下面是我的代码:

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, ListView} from 'react-native';
import axios from 'axios';

export default class App extends Component {

  constructor(props){
    super(props);
    this.state = {
      isolate: true,
      movies: []
    }

  }

  componentWillMount(){
    axios.get('https://facebook.github.io/react-native/movies.json')
    .then(function (response){
      var moviesList = new ListView.DataSource({
        rowHasChanged: (r1,r2) => r1 !== r2
      });
      this.setState({
        isolate: false,
        movies: moviesList.cloneWithRows(response.data.movies)
      });
    }).catch(function(error){
alert(error);
    });
  }
  render() {
if(this.state.isolate){
  return (<View>

    <Text>Loading....</Text>
  </View>);
}

    return (
      <View style={styles.container}>
        <ListView 
        dataSource={this.state.movies}
        renderRow={
          (rowData) => <Text> {rowData.title} </Text>
        }
        >
        </ListView>
      </View>
    );
  }
}

提前致谢。

标签: reactjsreact-nativeaxios

解决方案


您应该使用箭头函数作为回调:

axios.get('https://facebook.github.io/react-native/movies.json')
    .then(response => {
        // ...
    }

有关更多详细信息,请阅读如何在回调中访问正确的 `this`?了解如何this工作。


推荐阅读