在异步任务中获取上下文

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

我试图在异步任务中setState但我收到以下错误:

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

我在谷歌搜索,我发现错误的含义是我在异步任务中没有上下文,我怎么能正确地获得这个上下文?

当请求成功时,代码在加载运行时发送请求我想要setState来停止加载并读取请求响应。

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'
  },
});
reactjs react-native
1个回答
0
投票

在JS中,您可以在类中定义方法,如下所示:

class Test {

  myfunction() {
    // do something
  }
}

这将允许您致电this.myfunction()

所以编辑你的代码从getData = () => {...}getData() {...},你可以在app组件中调用this.getData()

© www.soinside.com 2019 - 2024. All rights reserved.