在异步任务中获取上下文

时间:2019-04-11 10:47:15

标签: reactjs react-native

我正在尝试在异步任务中设置setState,但是出现以下错误:

_this3.setState不是函数。 (在'_this3.setState({     数据源:responseJson.movi​​es,     isLoading:否   })','_ this3.setState'未定义)

我在google中搜索,发现错误的含义是我在异步任务中没有上下文,如何才能正确获取此上下文?

代码在加载运行时发送一个请求,当请求成功后我要设置状态以停止加载并读取请求响应。

import React from 'react';
import { StyleSheet, Text, View, Button, ListView, ActivityIndicator } from 'react-native';

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dataSource: null,
      isLoading: true
    };
  }

  componentDidMount() {
    getData();
  }

  render() {
    if (this.state.isLoading) {
      return (
        <View style={styles.container}>
          <ActivityIndicator size="large" />
        </View>
      );
    } else {
      return (
        <View style={styles.container}>
          {/* { 
            this.state.loading &&
            <View style={styles.loading}>
              <ActivityIndicator size='large' />
            </View>
          } */}

          <Text>Open up App.js to start working on your app!</Text>

          <Button
            onPress={() => {
              this.getData();
              this.state.loading = true;
            }}
            title="Get data"
            color="#841584"
            accessibilityLabel="Learn more about this purple button"
          />

        <ListView
          style={styles.container}
          dataSource={this.state.dataSource}
          renderRow={(data) => <View><Text>{data}</Text></View>}
        />

        </View>
      );
    }
  }

  getData = () => {
    getMoviesFromApiAsync();
  }

  getMoviesFromApiAsync = () => {
    return fetch('https://facebook.github.io/react-native/movies.json')
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({
          dataSource: responseJson.movies,
          isLoading: false
        });
        console.log("end");
      })
      .catch((error) => {
        console.error(error);
      });
  }
}


const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },

  loading: {
    position: 'absolute',
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
    alignItems: 'center',
    justifyContent: 'center'
  },
});

1 个答案:

答案 0 :(得分:0)

在JS中,您可以在这样的类中定义方法:

class Test {

  myfunction() {
    // do something
  }
}

这将允许您呼叫this.myfunction()

因此,将代码从getData = () => {...}修改为getData() {...},您应该可以在App组件内调用this.getData()