首页 > 解决方案 > 我坚持更改方法。正确地将 JSON 提取到正常方法

问题描述

在此处输入图像描述

export default class App extends Component {
  state = {
    currentCategory: "",
    products: [],
    cart: []
  };

  componentDidMount() {
    this.getProducts();
  }
  changeCategory = category => {
    this.setState({
      currentCategory: category.categoryName
    });
    this.getProducts(category.id);
  };

  getProducts = categoryId => {
    let url = "http://localhost:3000/products";
    if (categoryId) {
      url += "?categoryId=" + categoryId;
    }
    fetch(url)
      .then(response => response.json())
      .then(data => this.setState({
        products: data
      }));
  };

/////////////////////////////////////////

export default class App extends Component {
  state = {
    currentCategory: "",
    products: [],
    cart: []
  };

  componentDidMount() {
    this.getProducts();
  }
  changeCategory = category => {
    this.setState({
      currentCategory: category.categoryName
    });
    this.getProducts(category.id);
  };

  getProducts = (categoryId) => {
    var item = db.products;
    console.log(item.categoryId);
    this.setState({
      products: item
    });

  }
}

/////Json格式如下图//////

{
  "products": [{
    "id": 1,
    "categoryId": 1,
    "productName": "Chai",
    "quantityPerUnit": "48 - 6 oz jars",
    "unitPrice": 23,
    "unitsInStock": 53
  }],
  "categories": [{
    "id": "1",
    "categoryName": "Beverages",
    "seoUrl": "beverages"
  }]
}

当我从 api 获取数据时,这第一部分工作正常。但是当我想从本地获取 json 数据时,我可以但不能作为第一种方法正常工作。在第一种方法中过滤产品,categoryId 但我无法处理此过滤器。
console.log(item.categoryId);使用此代码,我尝试查看是否可以在控制台上获得正确的 id 项目,但我只能看到未定义的项目,如果我使用 this.setState({products:item.categoryId});,那么我会收到关于map函数的错误。

在这张图片中,当我单击左侧的一个类别时,它会过滤产品的右侧。我只能使用我无法正确更改的第一个代码。

标签: javascriptjsonreactjsfetch

解决方案


推荐阅读