【发布时间】:2021-02-09 09:01:11
【问题描述】:
尝试使用钩子在函数式中重写类组件。我重写了方法,但是敲掉了我不传输数据的错误,我不明白如何传输。错误说
undefined 不是对象(评估 `data[imageKey].urls`)。
我通过imgsource={{ url: modalImage }}渲染图片却出现错误
import React, { Component, useEffect, useState, useCallback } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TouchableWithoutFeedback,
Dimensions,
Modal,
ScrollView,
ActivityIndicator,
} from 'react-native';
import ImageElement from './ImageElement'
const ImageListWithHooks = (props) => {
useEffect(() => {
fetch('https://api.unsplash.com/photos/?client_id=cf49c08b444ff4cb9e4d126b7e9f7513ba1ee58de7906e4360afc1a33d1bf4c0')
.then((response) => response.json())
.then((json) => setData(json))
.catch((error) => console.log(error))
.finally(() => setLoading(false));
}, []);
const [loading, setLoading] = useState()
const [data, setData] = useState([]);
const [modalVisible, setModalVisible] = useState(false)
const [modalImage, setModalImage] = useState(props.imgsource)
const setModal = ((visible, imageKey) => {
setModalImage({ modalImage: visible ? data[imageKey].urls.raw : null })
setModalVisible({ modalVisible: visible })
})
let images = data.map((val, key) => {
return <TouchableWithoutFeedback key={key}
onPress={() => { setModal(key) }}>
<View style={styles.imagewrap}>
<ImageElement
author={{ url: val.user.profile_image.small }} // фото автора
imgsource={{ url: val.urls.small }} // работа автора
authorNameProp={val.user.name} // имя автора
></ImageElement>
</View>
</TouchableWithoutFeedback>
});
return (
<ScrollView>
<View style={styles.container}>
<Modal
style={styles.modal}
animationType={'fade'}
transparent={true}
visible={modalVisible}
onRequestClose={() => { }}
>
<View style={styles.modal}>
<Text style={styles.text}
onPress={() => { setModal(true) }}>Close</Text>
<View>
<Text style={styles.spinner}>Loading... <ActivityIndicator /></Text>
</View>
<ImageElement
imgsource={{ url: modalImage }}
></ImageElement>
</View>
</Modal>
{images}
</View>
</ScrollView>
);
}
【问题讨论】:
-
我最近是否帮助您编写了一些看起来非常相似的代码?您在
onPress={() => { setModal(key) }}中有一个错误,您将key传递给visible参数,而imageKey在您的setModal回调中未定义。我想我记得以前的代码中有一个类似的问题。data[undefined]产生undefined并且您无法访问urls属性。 -
因此,在我编写类组件时,在前面的代码中也出现了类似的错误。到目前为止,我不明白如何纠正这个错误。
-
我检查了您的响应数据,数组中的所有元素似乎都具有
urls.raw属性。您是否尝试解决我上面指出的问题?您应该始终将visible和imageKey参数传递给setModal。 -
所以我尝试解决调用 setModal 时会打开一个模态窗口的问题。我不太明白我必须如何始终如一地传达论点。
-
你的图像元素周围有一个按钮,它只传递一个
key(onPress={() => { setModal(key) }}),而模态中的另一个按钮只传递一个布尔值visible(onPress={() => { setModal(true) }}。你'已经定义setModal来使用visible和imageKey参数。如果您可以再次描述您希望用户与这两个按钮交互时所需的行为,我可以建议一个更有针对性的解决方案。如果我有猜测一下,您希望模态在按下图像时打开/可见,并在按下模态的关闭按钮时关闭/不可见,是吗?
标签: reactjs react-native