undefined不是一个函数(评估'this.setstate([重复]]

问题描述 投票:0回答:3

这个问题在这里已有答案:

我是原生初学者的反应。我已经使用“axios”npm包编写了一个从API获取数据的代码。当我运行正常运行但是当它获取数据时它是抛出错误。

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

提前致谢。

reactjs react-native axios
3个回答
2
投票

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

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

有关更多详细信息,请阅读How to access the correct `this` inside a callback?以了解this的工作原理。


1
投票

你的this语境在ajax调用的then中是未知的。您可以使用箭头函数来传递this的上下文,或者在ajax调用之前定义变量var self = this并在回调中使用它,如self.setState...

componentWillMount(){
    axios.get('https://facebook.github.io/react-native/movies.json')
    .then((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);
    });
  }

0
投票

关于你的错误,它发生是因为你试图在错误的上下文中访问它。解决方案是使用箭头函数将正确的上下文绑定到this关键字。 我还建议您在componentDidMount生命周期方法中获取数据,使其变为:

componentDidMount() {
  axios.get('https://facebook.github.io/react-native/movies.json')
    .then(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);
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.