Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
563 views
in Technique[技术] by (71.8m points)

reactjs - Pass props to component: "Objects are not valid as a React child"

I'm trying to simply pass the Id of a clicked item to display on another page under a different component ("Cart") . At the bottom of the code below, I have a button containing <Cart test={product.id} /> which extracts the Id that I want to be displayed in "Cart" when the button is clicked.

However, I am instead getting an error message of:

Objects are not valid as a React child (found: object with keys {history, location, match, staticContext}). If you meant to render a collection of children, use an array instead.

Is there a simple syntax error?

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;

Cart

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;
question from:https://stackoverflow.com/questions/65837870/pass-props-to-component-objects-are-not-valid-as-a-react-child

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Component props are objects. You can read more about them in the official documentation.

You can either destructure the props of the Cart component:

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

or use explicitly test property of props:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...