【发布时间】:2019-10-08 20:11:41
【问题描述】:
我正在尝试使用useRef 挂钩为`data 数组中的每个项目创建一个引用,方法是执行以下操作:
const markerRef = useRef(data.posts.map(React.createRef))
现在,data 是通过 GraphQL 从外部获取的,需要时间才能到达,因此,在安装阶段,data 是 undefined。这会导致以下错误:
TypeError: 无法读取未定义的属性“0”
我尝试了以下方法但没有成功:
const markerRef = useRef(data && data.posts.map(React.createRef))
如何设置,以便我可以通过data 映射而不会导致错误?
useEffect(() => {
handleSubmit(navigation.getParam('searchTerm', 'default value'))
}, [])
const [loadItems, { called, loading, error, data }] = useLazyQuery(GET_ITEMS)
const markerRef = useRef(data && data.posts.map(React.createRef))
const onRegionChangeComplete = newRegion => {
setRegion(newRegion)
}
const handleSubmit = () => {
loadItems({
variables: {
query: search
}
})
}
const handleShowCallout = index => {
//handle logic
}
if (called && loading) {
return (
<View style={[styles.container, styles.horizontal]}>
<ActivityIndicator size="large" color="#0000ff" />
</View>
)
}
if (error) return <Text>Error...</Text>
return (
<View style={styles.container}>
<MapView
style={{ flex: 1 }}
region={region}
onRegionChangeComplete={onRegionChangeComplete}
>
{data && data.posts.map((marker, index) => (
<Marker
ref={markerRef.current[index]}
key={marker.id}
coordinate={{latitude: marker.latitude, longitude: marker.longitude }}
// title={marker.title}
// description={JSON.stringify(marker.price)}
>
<Callout onPress={() => handleShowCallout(index)}>
<Text>{marker.title}</Text>
<Text>{JSON.stringify(marker.price)}</Text>
</Callout>
</Marker>
))}
</MapView>
</View>
)
我正在使用useLazyQuery,因为我需要在不同的时间触发它。
更新:
根据@azundo 的建议,我已将useRef 修改为以下内容:
const dataRef = useRef(data);
const markerRef = useRef([]);
if (data && data !== dataRef.current) {
markerRef.current = data.posts.map(React.createRef);
dataRef.current = data
}
当我 console.log markerRef.current 时,我得到以下结果:
这很好。但是,当我尝试映射每个 current 并调用 showCallout() 以通过执行以下操作打开每个标记的所有标注时:
markerRef.current.map(ref => ref.current && ref.current.showCallout())
什么都不会被执行。
console.log(markerRef.current.map(ref => ref.current && ref.current.showCallout()))
这显示每个数组的 null。
【问题讨论】:
标签: reactjs react-native react-hooks react-native-maps