1

为什么我在 createSiteMap 函数上收到“无法读取属性 'cityLocation' of null”?只有 {propertyOwner} 属性具有未定义的值。

但是,我能够 console.log(propertyOwner) 并且我得到了值。以下是控制台日志的结果:

2 608432995a21dc4d28bc8748 SG

4 608434915a21dc4d28bc8762 我的

2 608fc2e15a21dc4d28bc886f 日本

2 60937f3b5a21dc4d28bc88f6 美国

import { api } from '@helpers/api'
import { BASE_URL } from '@helpers/config'
import Slugify from 'slugify'
import { generateAuthHeaders } from '@helpers/authHeaders'
import { API_TOKEN } from '@helpers/config'

const url = BASE_URL

const createSitemap = (listings, date) => `<?xml version="1.0" encoding="UTF-8"?>
  <sitemapindex xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 
    http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" 
    xmlns:xhtml="http://www.w3.org/1999/xhtml">
  
      ${listings
        .map(({ id, propertyOwner, listingName }) => {
          return `
              <sitemap>
                <loc>${`${url}rooms/for-rent/${id}/${Slugify(propertyOwner.cityLocation, { <<<--------------
                  lower: true,
                  strict: true,
                })}/rentalbee-at-${Slugify(propertyOwner.codeName, {
                  lower: true,
                  strict: true,
                })}/room-for-${Slugify(listingName, {
                  lower: true,
                  strict: true,
                })}`}</loc>
                <lastmod>${date}</lastmod>
              </sitemap>
            `
        })
        .join('')}
  </sitemapindex>
`

class SitemapId extends React.Component {
  static async getInitialProps({ res, query }) {
    const allRooms = await api.get(
      '/listings',
      {
        headers: generateAuthHeaders(null, 'application/json', API_TOKEN),
      },
      { params: { page: query.id } }
    )

    const date = new Date().toISOString().split('T')[0]

    allRooms.data.listings.map(({ listingName, id, propertyOwner }) =>
      console.log(listingName, id, propertyOwner.cityLocation)  <<---------------------
    )

    res.setHeader('Content-Type', 'text/xml')
    res.write(createSitemap(allRooms.data.listings, date))

    res.end()
  }
}

export default SitemapId
4

1 回答 1

1

instead of this:

console.log(listingName, id, propertyOwner.cityLocation)  <<---------------------
    )

Try to test this

console.log(listingName, id, propertyOwner[id].cityLocation)

Clue: last parameter is same as original object in map function

propertyOwner <=> allRooms.data.listings
于 2021-05-10T17:53:58.230 回答