无法读取属性“地图" [英] Cannot read property 'map'

查看:35
本文介绍了无法读取属性“地图"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从无头 CMS (Sanity.io) 返回一些数据,但我的 React 不断遇到错误.我遵循了这个 example 但现在有错误 TypeError: Cannot read property 'map' of undefined

我的代码

import * as React from "react";从@sanity/client"导入 sanityClient;从reactstrap"导入{容器,行};const 客户端 = sanityClient({projectId: "<已编辑>",数据集:<已编辑>",useCdn: 真});让 dataHenter;const 查询 = `*[_type == "land"]`;导出默认类 CountryList 扩展 React.Component {构造函数(道具){超级(道具);this.state = {国家: []};}静态异步 getInitialProps() {返回 {国家:等待 client.fetch(query)};}使成为() {const { country } = this.props;返回 (<容器><div className="国家"><ul className="list">{country.map(country => (<li key={country._id}><行><a>{country.image}<h3>{country.name}</h3></a></行>))}

</容器>);}}

对我做错了什么有任何想法吗?

解决方案

当你的组件被渲染时,country 可能是 undefined 或 null.确保它在初始渲染时是数组:

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

或者,用

const { country } = this.props;

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

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

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

I am trying to return some data from a headless CMS (Sanity.io) but keep bumping into errors with my React. I've followed this example but now have the error TypeError: Cannot read property 'map' of undefined

My code

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>
    );
  }
}

Any ideas on what I am doing wrong?

解决方案

While your component is being rendered, it's possible to country be undefined or null. Make sure it to be array at initial render:

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

Or, with

const { country } = this.props;

You may use map with country like this:

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

This will ensure to run map only when there's country.

这篇关于无法读取属性“地图"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆