繁体   English   中英

错误:对象作为 React 子对象无效/无法映射我的 div 中的元素

[英]Error: Objects are not valid as a React child / can not map elements in my divs

当我尝试映射通过 Axios 获取的数据时出现此错误:

Error: Objects are not valid as a React child (found: object with keys {id, title}). If you meant to render a collection of children, use an array instead.
    in span (at ProductList.js:64)
    in div (created by ItemMeta)
    in ItemMeta (at ProductList.js:63)
    in div (created by ItemContent)
    in ItemContent (at ProductList.js:61)
    in div (created by Item)
    in Item (at ProductList.js:58)
    in div (created by ItemGroup)
    in ItemGroup (at ProductList.js:55)
    in div (created by Container)
    in Container (at ProductList.js:38)
    in ProductList (created by Context.Consumer)
    in Route (at routes.js:10)
    in Hoc (at routes.js:8)
    in BaseRouter (at App.js:18)
    in div (at Layout.js:22)
    in CustomLayout (created by Connect(CustomLayout))
    in Connect(CustomLayout) (created by Context.Consumer)
    in withRouter(Connect(CustomLayout)) (at App.js:17)
    in Router (created by BrowserRouter)
    in BrowserRouter (at App.js:16)
    in App (created by Connect(App))
    in Connect(App) (at src/index.js:21)
    in Provider (at src/index.js:20)

这是我的组件产品的相关代码:

import {
  Button,
  Container,
  Dimmer,
  Icon,
  Image,
  Item,
  Label,
  Loader,
  Message,
  Segment,
} from "semantic-ui-react";

import Axios from "axios";
import React from "react";
import { productListURL } from "../constants";

class ProductList extends React.Component {
  state = {
    loading: false,
    error: null,
    data: [],
  };
  componentDidMount() {
    this.setState({ loading: true });
    Axios.get(productListURL)
      .then((res) => {
        this.setState({ data: res.data, loading: false });
      })
      .catch((err) => {
        this.setState({ error: err, loading: false });
      });
  }
  render() {
    const { data, error, loading } = this.state;

    return (
      <Container>
        {error && (
          <Message
            negative
            header="there is error in your submission"
            content={JSON.stringify(error)}
          />
        )}
        {loading && (
          <Segment>
            <Dimmer active>
              <Loader>Loading</Loader>
            </Dimmer>

            <Image src="" />
          </Segment>
        )}
        <Item.Group divided>
          {data?.map((product) => {
            return (
              <Item key={product.id}>
                <Item.Image src={product.image} />

                <Item.Content>
                  <Item.Header as="a">{product.title}</Item.Header>
                  <Item.Meta>
                    <span className="cinema">{product.category}</span>
                  </Item.Meta>
                  <Item.Description>{product.description}</Item.Description>
                  <Item.Extra>
                    <Button primary floated="right" icon labelPosition="right">
                      Add to cart
                      <Icon name="cart plus" />
                    </Button>
                    <Label>{product.price}</Label>
                  </Item.Extra>
                </Item.Content>
              </Item>
            );
          })}
        </Item.Group>
      </Container>
    );
  }
}

export default ProductList;

我也尝试添加Fragment并将键放在 Fragment 上,但总是出现相同的错误,我检查了许多类似的问题和答案并尝试更改代码,但我总是收到相同的错误,任何帮助将不胜感激,谢谢

根据一些评论,这是对问题的更新:这里是数据的 console.log:

[]
length: 0
__proto__: Array(0)
ProductList.js:36 
(2) [{…}, {…}]
0:
category: {id: 1, title: "clothes"}
description: "a black T-shirt for men and women (unisex)"
discount_price: null
id: 1
image: "http://127.0.0.1:8000/media/duo.jpg"
price: 24
slug: "tshirt-black"
title: "Tshirt black"
__proto__: Object
1:
category: {id: 1, title: "clothes"}
description: "White T-shirt for men and women unisex"
discount_price: null
id: 2
image: "http://127.0.0.1:8000/media/2_00d6bb1f5b-asket_tee_white_cart_thumb-original.jpg"
price: 25
slug: "tshirt-white"
title: "Tshirt white"
__proto__: Object
length: 2
__proto__: Array(0)

在此处输入图片说明

您的 product.category 是一个对象 ({id, title})。 所以你不能简单地显示它。 我猜你想显示类别标题? 试试这个:

  import {
      Button,
      Container,
      Dimmer,
      Icon,
      Image,
      Item,
      Label,
      Loader,
      Message,
      Segment,
    } from "semantic-ui-react";
    
    import Axios from "axios";
    import React from "react";
    import { productListURL } from "../constants";
    
    class ProductList extends React.Component {
      state = {
        loading: false,
        error: null,
        data: [],
      };
      componentDidMount() {
        this.setState({ loading: true });
        Axios.get(productListURL)
          .then((res) => {
            this.setState({ data: res.data, loading: false });
          })
          .catch((err) => {
            this.setState({ error: err, loading: false });
          });
      }
      render() {
        const { data, error, loading } = this.state;
    
        return (
          <Container>
            {error && (
              <Message
                negative
                header="there is error in your submission"
                content={JSON.stringify(error)}
              />
            )}
            {loading && (
              <Segment>
                <Dimmer active>
                  <Loader>Loading</Loader>
                </Dimmer>
    
                <Image src="" />
              </Segment>
            )}
            <Item.Group divided>
              {data?.map((product) => {
                return (
                  <Item key={product.id}>
                    <Item.Image src={product.image} />
    
                    <Item.Content>
                      <Item.Header as="a">{product.title}</Item.Header>
                      <Item.Meta>
                        <span className="cinema">{product.category.title}</span>
                      </Item.Meta>
                      <Item.Description>{product.description}</Item.Description>
                      <Item.Extra>
                        <Button primary floated="right" icon labelPosition="right">
                          Add to cart
                          <Icon name="cart plus" />
                        </Button>
                        <Label>{product.price}</Label>
                      </Item.Extra>
                    </Item.Content>
                  </Item>
                );
              })}
            </Item.Group>
          </Container>
        );
      }
    }
    
    export default ProductList;

标签内的 HTML 内容应该是一个字符串。

<p>Hello</p>
<a>Contact Us</a>

如前所述, category键不是字符串。 它是一个具有属性{ id, title}的对象。 你在 a 中渲染它,而 React 抛出同样的错误。 (检查错误堆栈跟踪中的第二行)。

您可以在span使用以下代码:

<span className="cinema">{product.category.title}</span>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM