我是React /编程新手,在获取/显示数据时遇到麻烦。我的代码返回以下错误。感谢您的帮助。
TypeError:TypeError:未定义不是对象(正在评估“ 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}
/>
)
}
答案 0 :(得分:1)
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}
/>
)
答案 1 :(得分:1)
我认为一开始没有数据,因此请使用默认分配
const { data = [] } = useFetch('http://192.168.2.94:3000/list-categories')
更新
const displayedCategories = data.filter(
cat => cat && cat.locId && cat.locId.indexOf(locations) >= 0
)