在 render() 中显示 featch json 数据时 React Native 出错
error in react Native while show featch json data in render()
我是 React 的新手 - 本机开发。我有这个 json 数据需要使用 {this.state.data.min.en}
在 render() 中显示
{
"status": true,
"message": "good",
"data": {
"min": {
"sin": "text",
"en": " text",
"ta": "text",
"ownere": " text"
}
}
}
代码:
import React, { Component } from "react";
import {
Platform,
StyleSheet,
Text,
View,
AppRegistry,
Alert
} from "react-native";
import { Card } from "react-native-elements";
export default class Home extends Component {
constructor() {
super();
this.state = {
data: []
};
}
handlePress = async () => {
fetch("http://xxx.xx.xx.xx/index.php/testCV/home", {
method: "POST",
headers: {
"Content-Type": "application/json"
}
})
.then(response => response.json())
.then(responseJson => {
this.setState({ data: responseJson.data });
})
.catch(error => {
console.error(error);
});
};
componentDidMount() {
this.handlePress();
}
render() {
return (
<View>
<Card>{this.state.data.min.en}</Card>
</View>
);
}
}
AppRegistry.registerComponent("Home", () => Home);
我尝试使用上面的代码但是当我 运行 它时我得到了这个错误。我试图找到修复它的方法,但没有成功。
非常感谢有人能帮我解决这个错误。
谢谢
您将数据默认为一个空数组,因此当您编写 this.state.data.min
时,您将得到 undefined
,然后尝试访问 en
将导致您的错误。
你可以,例如默认 data
为 null
,并等待数据加载后再呈现。
例子
export default class Home extends Component {
constructor(props) {
super(props);
this.state = {
data: null
};
}
// ...
render() {
const { data } = this.state;
if (data === null) {
return null;
}
return (
<View>
<Card>{data.min.en}</Card>
</View>
);
}
}
我是 React 的新手 - 本机开发。我有这个 json 数据需要使用 {this.state.data.min.en}
在 render() 中显示{
"status": true,
"message": "good",
"data": {
"min": {
"sin": "text",
"en": " text",
"ta": "text",
"ownere": " text"
}
}
}
代码:
import React, { Component } from "react";
import {
Platform,
StyleSheet,
Text,
View,
AppRegistry,
Alert
} from "react-native";
import { Card } from "react-native-elements";
export default class Home extends Component {
constructor() {
super();
this.state = {
data: []
};
}
handlePress = async () => {
fetch("http://xxx.xx.xx.xx/index.php/testCV/home", {
method: "POST",
headers: {
"Content-Type": "application/json"
}
})
.then(response => response.json())
.then(responseJson => {
this.setState({ data: responseJson.data });
})
.catch(error => {
console.error(error);
});
};
componentDidMount() {
this.handlePress();
}
render() {
return (
<View>
<Card>{this.state.data.min.en}</Card>
</View>
);
}
}
AppRegistry.registerComponent("Home", () => Home);
我尝试使用上面的代码但是当我 运行 它时我得到了这个错误。我试图找到修复它的方法,但没有成功。
非常感谢有人能帮我解决这个错误。 谢谢
您将数据默认为一个空数组,因此当您编写 this.state.data.min
时,您将得到 undefined
,然后尝试访问 en
将导致您的错误。
你可以,例如默认 data
为 null
,并等待数据加载后再呈现。
例子
export default class Home extends Component {
constructor(props) {
super(props);
this.state = {
data: null
};
}
// ...
render() {
const { data } = this.state;
if (data === null) {
return null;
}
return (
<View>
<Card>{data.min.en}</Card>
</View>
);
}
}