React-Native 状态未定义

React-Native state undefined

我第一次在 react-native 中使用 类 但由于某些原因我无法更改状态。我检查了它是否是 API 但 API 工作正常。 bootstrap 和其他一切正常,但 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)

setState无关。使用正常的class方法就可以了:

  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 是 class 属性,而不是 class 方法。我们可以用 es5 语法转换这些代码(忽略 async 和其他一些不必要的代码):

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

您需要将函数绑定到 this。所以更改以下行:

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

以下内容:

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

为了能够在函数中使用 this,您需要将其绑定到 class。所以解决这个问题的几种方法是:

创建箭头函数

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/>

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