【问题标题】:Passing props in react - fetching在反应中传递道具 - 获取
【发布时间】:2020-03-15 11:43:48
【问题描述】:

我只是试图通过组件传递道具并在 jsx 中渲染它,但不知何故这不起作用。我正在寻找问题,但找不到它。

我正在尝试从这个组件传递道具:

import React from "react";
import "../styles/Products.css";
import ProductItem from "../items/ProductItem";
class Products extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: []
    };
  }
  componentDidMount() {
    fetch("../products.json")
      .then(response => response.json())
      .then(response => this.setState({ data: response.products }));
  }
  render() {
    return (
      <div className="products-container">
        <ProductItem data={this.state.data[0]} />
      </div>
    );
  }
}
export default Products;

到这个组件:

import React from "react";
import "../styles/ProductItem.css";
const ProductItem = props => {
  console.log(props.data, "current");
  return (
    <div className="product-item">
      <img src="" alt="" className="bike-image" />
      <div className="active-product" />
      <div className="view-details">Compare</div>
      <h2>Bike</h2>
      <h4>downhill bike</h4>
      <p>3500 PLN</p>
    </div>
  );
};
export default ProductItem;

问题是当我查看react dev tools 时,props 已正确传递,但是当我尝试获取 props.data.id 等对象的属性时,出现错误:

无法读取未定义的属性“id”

【问题讨论】:

  • 您是否尝试仅控制台记录 props.data?
  • 是的,我已经得到了整个对象,并且它可以正常工作
  • 在对象中你的 ID 正确吗?
  • 没错。但我无法读取此对象的任何属性
  • 在你的console.log(props.data)的ProductItem组件中,你能附上那个console.log的截图吗?

标签: json reactjs fetch


【解决方案1】:

fetch 需要一些时间来获得响应并填充this.state.data 数组。所以你需要检查this.state.data[0] 值是否真的可用。你可以试试这个-

  render() {
    return (
      <div className="products-container">
       {this.state.data && this.state.data.length > 0 &&  <ProductItem data={this.state.data[0]} />}
      </div>
    );
  }

【讨论】:

  • 就是这样!非常感谢!
猜你喜欢
  • 2019-01-22
  • 2021-09-27
  • 2020-12-01
  • 1970-01-01
  • 2019-06-30
  • 2018-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多