gpt4 book ai didi

javascript - set.State 未定义

转载 作者:行者123 更新时间:2023-12-01 01:23:31 25 4
gpt4 key购买 nike

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

类型错误: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"
}
});

最佳答案

要将函数的上下文维持为按词法定义该函数的上下文,您必须使用 arrow function :

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
});
}
);
});
};

关于javascript - set.State 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54034980/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com