0

我有一个名为 isLoading 的状态变量。这个想法是在程序与服务器通信时显示加载消息,然后显示数据。但是,在 24 岁时,我收到一个错误:

TypeError: This.setState 不是函数(在 'this.setState({ isloadin: false});

import React from "react";
import { StyleSheet, Text, View, AsyncStorage } from "react-native";

var text;

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

  componentDidMount = () => {
    AsyncStorage.getItem("accessToken").then(token => {
      postdata(
        "http://1.0.0.0:1337/loadTransactions",
        { UserID: 69 },
        function(result) {
          text = toString(result.Data[1].ID);
          text = result.Data[1].Label;
          console.log(result.Data[1].Label);
          this.setState({
            isLoading: false
          });
        }
      );
    });
  };
  render() {
    console.log(this.setState.isLoading);

    if (this.setState.isLoading) {
      console.log(this.setState.isLoading);
      return (
        <View style={styles.container}>
          <Text>Loading....</Text>
        </View>
      );
    } else {
      return (
        <View style={styles.container}>
          <Text>Hi, {text}</Text>
          <Text>Test</Text>
        </View>
      );
    }
  }
}

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

2 回答 2

2

要将函数的上下文与词法定义函数的上下文保持一致,您必须使用箭头函数

componentDidMount = () => {
  AsyncStorage.getItem("accessToken").then(token => {
    postdata(
      "http://204.48.23.161:1337/loadTransactions",
      { UserID: 69 },
      function(result) {
    // ^^^^^^^ use `result => ` here
        text = toString(result.Data[1].ID);
        text = result.Data[1].Label;
        console.log(result.Data[1].Label);
        this.setState({
          isLoading: false
        });
      }
    );
  });
};
于 2019-01-04T07:55:04.737 回答
0

this(参考类的实例)可能在AsyncStorage. 另存this为另一个变量并在里面使用:

componentDidMount = () => {
  const self = this;
  AsyncStorage.getItem("accessToken").then(token => {
    postdata(
      "http://204.48.23.161:1337/loadTransactions",
      { UserID: 69 },
      function(result) {
        text = toString(result.Data[1].ID);
        text = result.Data[1].Label;
        console.log(result.Data[1].Label);
        self.setState({
          isLoading: false
        });
      }
    );
  });
};
于 2019-01-04T07:57:23.957 回答