React-Native状态未定义

时间:2019-12-16 15:06:21

标签: reactjs react-native reactjs-native

我第一次在react-native中使用类,但是由于某些原因,我无法更改状态。我检查了它是否是API,但该API正常运行。引导程序和其他所有功能都可以正常使用,但是this.setState({ name: response.data.name });出于某种原因无法正常工作。有人知道我在做什么错吗?

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

export default class Dashboard extends React.Component {
  constructor() {
    super();
    this.state = {
      token: "",
      response: [],
      supported: true,
      displayName: "",
      id: 0,
      name: "",
      phone: 0,
      website: ""
    };
    this._bootstrap();
  }

  _bootstrap = async () => {
    const token = await AsyncStorage.getItem("accessToken");
    this.setState({ token: token });
  };

  changeName = async function() {
    try {
      response = await axios.get("general/organization/own/default");
      this.setState({ name: response.data.name });
      return;
    } catch (error) {
      console.log(error);
      return;
    }
  };

  render() {
    return (
      <View style={styles.container}>
        <Text>name: {this.state.name}</Text>
        <Button title="change name" onPress={this.changeName} />
      </View>
    );
  }
}

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

错误: this.setState不是函数。 (In 'this.setState({name: response.data.name})', 'this.setState' is undefined)

3 个答案:

答案 0 :(得分:1)

要在函数内使用$TTL 7200 @ IN SOA ns-787.awsdns-34.net. awsdns-hostmaster.amazon.com. ( 2019121606 ; serial 7200 ; refresh 900 ; retry 1209600 ; expire 86400 ) ; minimum @ IN NS ns-787.awsdns-34.net. @ IN NS ns-194.awsdns-24.com. @ IN NS ns-1452.awsdns-53.org. @ IN NS ns-1880.awsdns-43.co.uk. ,您需要将其绑定到类。因此,您必须解决的几种方法是:

创建箭头功能

this

在构造函数上绑定函数

changeName = async () => {
  try {
    let { data: { name } } = await axios.get(url);
    this.setState({ name });
  } catch (err) {
    console.log(err);
  }
};

将其绑定到constructor(props) { this.state: {}, changeName: this.changeName.bind(this), }

<Button/>

答案 1 :(得分:0)

setState无关。使用普通的类方法就可以了:

  async changeName() {
    try {
      response = await axios.get("general/organization/own/default");
      this.setState({ name: response.data.name });
      return;
    } catch (error) {
      console.log(error);
      return;
    }
  };

多写一点...

实际上,代码中的changeName是类属性,而不是类方法。我们可以使用es5语法转换这些代码(忽略异步和其他一些不必要的代码):

function Dashboard() {
  ....
  defineProperty(this, 'changeName', async function() {
     // "this" here doesn't point to Dashboard context
     this.setState({ .... })
  })
}

答案 2 :(得分:0)

您需要将该函数绑定到 this 。因此,更改以下行:

<Button title="change name" onPress={this.changeName} />

到以下内容:

<Button title="change name" onPress={this.changeName.bind(this)} />