首页 > 解决方案 > 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')

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;

标签: reactjsreact-native

解决方案


尝试这个:

 const setModal = useCallback((visible, imageKey) => {
    setModalImage({ modalImage: visible ? data[imageKey].urls.raw : null })
    setModalVisible({ modalVisible: visible })
}, [data])

推荐阅读