我正在尝试从无头CMS(Sanity.io)返回一些数据,但是我的React一直遇到错误。我已遵循此示例,但是现在出现错误TypeError: Cannot read property 'map' of undefined
TypeError: Cannot read property 'map' of undefined
我的密码
import * as React from "react"; import sanityClient from "@sanity/client"; import { Container, Row } from "reactstrap"; const client = sanityClient({ projectId: "<redacted>", dataset: "<redacted>", useCdn: true }); let dataHenter; const query = `*[_type == "land"]`; export default class CountryList extends React.Component { constructor(props) { super(props); this.state = { country: [] }; } static async getInitialProps() { return { country: await client.fetch(query) }; } render() { const { country } = this.props; return ( <Container> <div className="country"> <ul className="list"> {country.map(country => ( <li key={country._id}> <Row> <a> {country.image} <h3>{country.name}</h3> </a> </Row> </li> ))} </ul> </div> </Container> ); } }
关于我在做什么错的任何想法吗?
渲染组件时,可以将country定义为未定义或为null。确保它在初始渲染时是数组:
const { country } = this.props || { country: [] };
或者,
const { country } = this.props;
您可以将地图用于这样的国家/地区:
{country && country.length && country.map(country => (
这样可以确保仅在有国家/地区时才运行地图。