将道具传递给组件:“对象作为 React 子对象无效”

时间:2021-01-22 00:48:24

标签: reactjs

我试图简单地传递被点击项目的 Id 以显示在不同组件(“购物车”)下的另一个页面上。在下面代码的底部,我有一个包含 <Cart test={product.id} /> 的按钮,它提取我想要在单击按钮时显示在“购物车”中的 ID。

但是,我收到了以下错误消息:

<块引用>

对象作为 React 子对象无效(找到:带有键的对象 {历史,位置,匹配,staticContext})。如果你想渲染一个 子集合,请改用数组。

是否有简单的语法错误?

import React, { useState, useEffect, Cart } from 'react';
import './../App.css';
import * as ReactBootStrap from 'react-bootstrap';

function Item(props) {
  const [product, setProduct] = useState([]);
  const [loading, setLoading] = useState(false);
  const [quantity, setQuantity] = useState(1);
  const [cost, setCost] = useState([]);

  useEffect(async () => {
    fetchItems();
  }, []);

  const itemId = props.match.params.item;
  const fetchItems = async () => {
    const data = await fetch('https://fakestoreapi.com/products/' + itemId);
    const items = await data.json();
    setProduct(items);
    setLoading(true);
    setCost(items.price);
  };

  function priceUSD(change) {
    return change.toFixed(2);
  }

  useEffect(() => {
    const newCost = quantity * product.price;
    setCost(priceUSD(newCost));
  }, [quantity]);

  return (
    <div className="App">
      <h2>Item</h2>
      <div className="gridContainer">
        {loading ? (
          <div key={itemId} className="productStyle">
            <img src={product.image} className="productImage"></img>
            <p>{product.title}</p>
            <p>{product.description}}</p>
            <p>${priceUSD(product.price)}</p>

            <div className="quantity">
              <button
                className="btn minus-btn"
                type="button"
                onClick={quantity > 1 ? () => setQuantity(quantity - 1) : null}
              >
                -
              </button>
              <input type="text" id="quantity" value={quantity} />
              <button className="btn plus-btn" type="button" onClick={() => setQuantity(quantity + 1)}>
                +
              </button>
            </div>

            <button type="button" onClick={() => <Cart test={product.id} />}>
              Add to shopping cart ${cost}
            </button>
          </div>
        ) : (
          <ReactBootStrap.Spinner className="spinner" animation="border" />
        )}
      </div>
    </div>
  );
}

export default Item;

购物车

import React, { useState, Item } from 'react';
import './../App.css';
import './Item.js';

function Cart(test) {
    return (
      <div className="App">
        <p>{test}</p>
      </div>
    );
}

export default Cart;

1 个答案:

答案 0 :(得分:0)

组件道具是对象。您可以在官方 documentation 中阅读有关它们的更多信息。

您可以解构 Cart 组件的 props:

function Cart({test}) {
    return (
      <div className="App">
        <p>{test}</p>
      </div>
    );
}

或显式使用 testprops 属性:

function Cart(props) {
    return (
      <div className="App">
        <p>{props.test}</p>
      </div>
    );
}