首页 > 解决方案 > React-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)

标签: reactjsreact-nativereactjs-native

解决方案


为了能够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/>

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

推荐阅读