TypeError:未定义不是一个对象(评估'data.filter') - React Native
2019-12-09
4675
我是 React/编程新手,在获取/显示数据时遇到问题。我的代码返回以下错误。提前感谢您的帮助。
TypeError:TypeError:undefined 不是对象(评估“data.filter”)
import useFetch from 'react-fetch-hook'
const { data } = useFetch('http://192.168.2.94:3000/list-categories')
const locations = props.navigation.getParam('locationId')
const displayedCategories = data.filter( // ERROR HERE
cat => cat.locId.indexOf(locations) >= 0
)
const renderGridItem = itemData => {
return (
<CategoryGridTile
image={itemData.item.image}
title={itemData.item.title}
/>
)
}
return (
<FlatList
keyExtractor={(item, index) => item.id}
data={displayedCategories}
renderItem={renderGridItem}
/>
)
}
2个回答
useFetch
返回一个
isLoading
标志以及数据,您必须使用该标志来显示加载指示器,直到数据可用
const { isLoading, data } = useFetch('http://192.168.2.94:3000/list-categories');
if(isLoading) {
return <span>Loading...</span>
}
const locations = props.navigation.getParam('locationId')
const displayedCategories = data.filter(
cat => cat.locId.indexOf(locations) >= 0
)
const renderGridItem = itemData => {
return (
<CategoryGridTile
image={itemData.item.image}
title={itemData.item.title}
/>
)
}
return (
<FlatList
keyExtractor={(item, index) => item.id}
data={displayedCategories}
renderItem={renderGridItem}
/>
)
Shubham Khatri
2019-12-09
我认为开始时没有数据,因此请使用默认分配
const { data = [] } = useFetch('http://192.168.2.94:3000/list-categories')
更新
const displayedCategories = data.filter(
cat => cat && cat.locId && cat.locId.indexOf(locations) >= 0
)
Jay
2019-12-09