[Front-end debug] Carousel chart error TypeError: Cannot read properties of undefined (reading 'topModule')

Article directory

bug

When writing a carousel, an error is reported:

TypeError: Cannot read properties of undefined (reading ‘topModule’)

It shows that mainPart does not exist, but the picture is displayed.

insert image description here

Corresponding code:
html:

<detailSwipe :swipe-data="detailData.mainPart.topModule.housePicture.housePics"/>
<!-- 轮播图 -->
<template>
    <div class="swipe">
        <van-swipe class="my-swipe" :autoplay="3000" lazy-render>
            <van-swipe-item v-for="item in props.swipeData" :key="item">
                <img :src="item.albumUrl" />
            </van-swipe-item>
        </van-swipe>
    </div>
</template>

<script setup>
const props = defineProps({
      
      
    swipeData: {
      
      
        type: Array,
        default: () => []
    }
})

</script>

js:

const detailStore = useDetailStore()

detailStore.fetchDetailData(houseId)
const {
    
     detailData } = storeToRefs(detailStore)

fetchDetailData

import {
    
     defineStore } from "pinia";
import {
    
     getDetailInfos } from '@/service/modules/detail'

const useDetailStore = defineStore('detail', {
    
    
    state: () => {
    
    
        return {
    
    
            detailData: {
    
    },

        }
    },
    actions: {
    
    
        async fetchDetailData(houseId) {
    
    
            const res = await getDetailInfos(houseId)
            // console.log(res)
            this.detailData=res.data
        }
    }
})

export default useDetailStore

debug

The console error shows that mainPart does not exist, but the page shows that mainPart exists. Explanation: MainPart did not exist at first, but then it existed again.

Analyzing the code, it is found detailDatathat it is responsive , and the data of is obtained detailDatathrough network requests , and network requests take time.fetchDetailData

At the beginning of the page rendering, no data is requested yet. At this time, the mainPart does not exist, and the console will report an error. After the data is requested by the network, it exists. The page displays the data, but the error will not be cancelled.

Although this error report does not affect the display of the page (?), we still have to solve it.

Workaround 1: Optional chaining operator?.

<detailSwipe :swipe-data="detailData?.mainPart?.topModule?.housePicture?.housePics"/>

Useful but cumbersome, too much ?.

Solution 2:v-if

 <div class="main" v-if="detailData.mainPart">
     <detailSwipe :swipe-data="detailData.mainPart.topModule.housePicture.housePics" />
 </div>

No more errors.
insert image description here

Guess you like

Origin blog.csdn.net/karshey/article/details/128901625
Recommended