无法读取属性“地图”

时间:2018-08-15 16:08:01

标签: reactjs

我正在尝试从无头CMS(Sanity.io)返回一些数据,但是我的React一直遇到错误。我已遵循此example,但现在遇到错误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 个答案:

答案 0 :(得分:1)

正在渲染您的组件时,可能无法定义country或为null。确保它在初始渲染时是数组:

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

或者,用

const { country } = this.props;

您可以将地图与这样的国家一起使用:

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

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