javascript - 我坚持更改方法。正确地将 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
函数的错误。
在这张图片中,当我单击左侧的一个类别时,它会过滤产品的右侧。我只能使用我无法正确更改的第一个代码。
解决方案
推荐阅读
- swift - 调度到 Swift 协议扩展
- shell - “grep -B 1”是否有任何替代方法,因为我不能使用 grep 和 -B 来获取 o/p
- javascript - Video.js:使视频保持最大高度的纵横比
- amazon-web-services - 从 Terraform 输入变量中获取 ECS 任务定义环境变量
- javascript - Apache-arrow JS 实现
- c# - 找出 URL 是否存在的绝对最安全的方法是什么?
- r - 在 R Shiny 应用程序中并排生成 UI 元素
- java - 如何在android的firebase中删除多个值?
- jupyter-notebook - 如何为anacadona安装漂亮的汤?
- javascript - 处理具有相同 id 值的多个元素不起作用