javascript - (语法?)this.state 不是 componentDidMount 中的函数错误和排序
问题描述
我不断收到 TypeError: this.state.pageOfItems is not a function,我无法理解它。这可能是语法问题。另外我还有另一个问题:我正在尝试使用 array.sort 按 componentDidMount 中每个产品的分数降序对每个产品进行排序,这似乎也不起作用。非常感谢您提前。
import React from 'react';
import JwPagination from 'jw-react-pagination';
class Products extends React.Component {
constructor(props) {
super(props);
this.state = {
productItems: [{
id: '0',
title: '1',
price: 50,
score: 20,
}, {
id: '1',
title: '2',
price: 30,
score: 30,
},
],
pageOfItems:[],
}
this.onChangePage = this.onChangePage.bind(this);
this.displayProducts = this.displayProducts.bind(this);
}
onChangePage(pageOfItems) {
this.setState({pageOfItems})
}
componentDidMount() {
var products = this.state.productItems;
this.setState({productItems: products.sort(function(a,b){return
b-a})});
}
displayProducts() {
let itemList = this.state.pageOfItems(item=>{
return(
<div className="card" key={item.id}>
<div className="card1">
<span className="card-title">{item.title}</span>
</div>
<div className="card-content">
<p>price: {item.price}</p>
</div>
</div>
)
})
return itemList;
}
render() {
return(
<div>
<h3 className="center"> Products </h3>
<JwPagination items={this.state.productItems} onChangePage=
{this.onChangePage} pageSize={5}/>
{this.displayProducts()}
</div>
)
}
}
export default Products;
解决方案
您似乎将数组与在数组上forEach
找到的方法混淆了。
const foo = [3, 2, 1];
foo.forEach(item => {
console.log(item);
});
推荐阅读
- css - Django - 管理区域宽度
- bash - Bash/Awk 比较两个文件,在坐标之间打印值,否则打印 0
- android - 如何在背景图像上添加多个图像
- google-apps-script - 如何在谷歌表格中的类似日期条目之后自动添加一个空白行?
- unity3d - Unity弹跳球奇迹般地长高了
- python - 通过给定范围的属性查询弹性搜索索引?
- javascript - 单击图像时如何将文本复制到剪贴板?
- javascript - 在 URL 更改时移除注入的 iframe | Chrome 扩展程序
- idris - 在签名中找不到具有约束的实现
- python - 在 graphql 查询中包含参考字段