reactjs - TypeError: undefined is not an object (评估 'data[imageKey].urls')
问题描述
错误说 undefined is not an object (evalating.data [imageKey] .urls) 我没有正确传递 URL。TypeError: undefined is not an object (评估 'data[imageKey].urls')
- node_modules\react-native\Libraries\LogBox\LogBox.js:148:8 in registerError
- node_modules\react-native\Libraries\LogBox\LogBox.js:59:8 in errorImpl
- node_modules\react-native\Libraries\LogBox\LogBox.js:33:4 in console.error
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 }}>Close</Text>
<View>
<Text style={styles.spinner}>Loading... <ActivityIndicator /></Text>
</View>
<ImageElement
imgsource={{ url: modalImage }}
></ImageElement>
</View>
</Modal>
{images}
</View>
</ScrollView>
);
}
export default ImageListWithHooks;
解决方案
尝试这个:
const setModal = useCallback((visible, imageKey) => {
setModalImage({ modalImage: visible ? data[imageKey].urls.raw : null })
setModalVisible({ modalVisible: visible })
}, [data])
推荐阅读
- c++ - 带有 -O3 警告的特征:参数 1 值“X”超过最大对象大小 Y
- powerbi - 使用 Power BI 和 Cortana 的会话分析
- excel - 检测非标准符号
- flutter - Flutter - 推送通知单击重定向到特定屏幕不起作用
- c++ - 如何获取 QGraphicsView 中加载的图像像素位置 - 奇怪的 MapToScene() 行为
- javascript - Compare hours with google-script
- javascript - 在 3 分钟后暂停来自 chrome 控制台的 youtube 视频
- android - Error: Program type already present: org.intellij.lang.annotations.JdkConstants$PatternFlags 2
- javascript - How can i filter array on object in javascript
- xamarin - Xamarin 表单中的数据绑定条目