json - 我有这个问题未定义不是一个对象(评估'this.state.dataSource.map')
问题描述
我想显示来自在线 json url 的地点列表。
import React, { Component } from "react";
import {
View,
StyleSheet,
Dimensions,
Image,
StatusBar,
TextInput,
TouchableOpacity,
Text,
Button,
Platform,
Alert,
FlatList,
ActivityIndicator,
} from "react-native";
let url = "https://cz2006api.herokuapp.com/api/getAll";
let url2 = "";
export default class ClinicComponent extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
dataSource: null,
};
}
componentDidMount() {
return fetch("https://cz2006api.herokuapp.com/api/getAll")
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson.data.data,
});
})
.catch((error) => {
console.log(error);
});
}
render() {
if (this.state.isLoading) {
return (
<View style={styles.container}>
<ActivityIndicator />
</View>
);
} else {
let hospitals = this.state.dataSource.map((val, key) => {
return (
<View key={key} style={styles.item}>
<Text>{val.name}</Text>
</View>
);
});
return (
<View style={styles.item}>
{/* <Text>Content Loaded</Text> */}
{hospitals}
</View>
);
}
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
},
item: {
flex: 1,
alignSelf: "stretch",
margin: 10,
alignItems: "center",
justifyContent: "center",
borderBottomWidth: 1,
borderBottomColor: "#eee",
},
});
不幸的是,当我尝试通过 expo cli 运行它时出现错误,说 undefined is not an object enter image description here
任何人都可以帮助我吗?我只想有一个可滚动的医院列表。谢谢!Json 的 URL 在这里:https ://cz2006api.herokuapp.com/api/getAll
解决方案
只需将您的初始状态更改为这样的
this.state = {
isLoading: true,
dataSource: [], // <-- here
};
您的问题是您正在使用dataSource.map
但在 api 调用期间您dataSource
仍然保持 null 直到它得到响应,并且 null 对象没有属性map
。这就是你的问题的原因。
推荐阅读
- scala - Scala 匹配和引用相等性检查
- node.js - socket.io 可以在发送到特定客户端时支持回调吗?
- wordpress - 旋转滑块第一帧的字母 A 是什么意思?
- typo3 - FrontendUser 中的附加字段未保存
- javascript - Angular 6:调用 HTTP 请求后未设置类的属性
- css - Map 上的 @each 循环不会用值替换变量,而是在 SASS 中打印变量名
- firebase - Firebase(firestore)规则:仅在更新另一个文档时确保更新(FieldValue 增加)?
- c# - 如何确定 .NET 程序集是否使用平台目标 AnyCPU、AnyCPU Prefer32 位、x86、x64 构建,而不使用反射和第三方软件
- reactjs - 在 React 中将深度嵌套的 JSON 对象传递给 PureComponent 道具的最佳方法是什么?
- javascript - 用户更改类型时添加新类