reactjs - 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)
解决方案
为了能够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)} />
推荐阅读
- react-native - Nativebase - 单击输入时如何显示日期选择器?
- clojure - 当我使用函数文字时,我不理解 ArityException
- javafx - 如何仅关闭 Java FX 中的一个阶段(不退出所有应用程序)?
- ios - 如何使用 Visual Format Language 在 Swift 中设置约束?
- winapi - 如何使用 winapi crate 为 Windows 制作托盘图标?
- c++ - 如何在 WinForm GUI 中使用 Crypto++?
- javascript - 从 html 或 javascript 到 python Django 的通信
- x86 - 像 Denormals-Are-Zero (DAZ) 这样的非正规标志会影响相等比较吗?
- java - 如何使用最新的 Google Sign-In and Drive REST api 上传 SQLite 数据库文件?
- solr - SOLR,如何在 SOLR UI 中设置allowleadingwildcard?