在 React 中获取 [object Object] 而不是 object

Getting [object Object] instead of object in React

我正在我的 React 应用程序中获取一组对象。稍后我将向每个对象返回一个 Product 组件。

 const [products, setProducts] = useState([]);

  useEffect(() => {
    fetch("http://localhost:8080/products")
      .then(resp => resp.json())
      .then(resp => {
        console.log(resp); //line 55
        setProducts(resp)
      })
  }, []);

  return (
      <div>
        {products.map(product => {
          return <Product product={product} />
        })}
      </div>
  );

这是我在第 55 行 console.log(resp) 的结果:

    Array(6) [ {…}, {…}, {…}, {…}, {…}, {…} ]
​
0: Object { id: 1, name: "prod 3", amount: 30, … }
​​
active: true
​​
amount: 30
​​
id: 1
​​
name: "prod 3"
​​
<prototype>: Object { … }
​
1: Object { id: 23, name: "prod 2", amount: 20, … }
​
2: Object { id: 4, name: "Angular course", amount: 19, … }
​
3: Object { id: 42, name: "peanut butter", amount: 13, … }
​
4: Object { id: 43, name: "soup", amount: 12, … }
​
5: Object { id: 15, name: "hot-dog", amount: 11, … }
​

​
length: 6
​
<prototype>: Array []

所以我将单个对象传递到我的 Product 组件。但是,当我想在日志中查看传递的对象时,我得到了对象内部的对象:

 const Product = (product) => {
      console.log(product); // result: Object { product: {…} }
 }

为什么我得到的是对象内部的对象而不是单个对象?

在 React 中,组件的参数始终是它们的 props 对象。这是一个具有您在标签中定义的所有属性的对象。因此,例如,如果您定义 <Product anotherProp={anotherProp} product={product} />,您将获得一个带有键 productanotherPropprops 对象。 所以获得 product 的正确方法是通过解构赋值。

const Product = (props) => {
      const {product} = props;
      console.log(product); // result: Object { product: {…} }
 }

如果你希望你的道具对象正是你的产品对象,你必须改变你设置标签的方式......在你的情况下,它会是这样的......

 const [products, setProducts] = useState([]);

  useEffect(() => {
    fetch("http://localhost:8080/products")
      .then(resp => resp.json())
      .then(resp => {
        console.log(resp); //line 55
        setProducts(resp)
      })
  }, []);

  return (
      <div>
        {products.map(product => {
          return <Product {...product} />
        })}
      </div>
  );