无法读取属性“地图”

IT技术 reactjs
2021-04-23 23:10:54

我正在尝试从无头 CMS (Sanity.io) 返回一些数据,但我的 React 不断遇到错误。我已经按照这个例子,但现在有错误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>
    );
  }
}

关于我做错了什么的任何想法?

1个回答

当您的组件正在呈现时,country 可能是 undefined 或 null。确保它在初始渲染时是数组:

const { country } = this.props || { country: [] };

或者,与

const { country } = this.props;

您可以像这样使用带有国家/地区的地图:

{country && country.length && country.map(country => (

这将确保仅在有国家/地区时才运行地图。