首页 > 解决方案 > (语法?)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;

标签: javascriptreactjs

解决方案


您似乎将数组与在数组上forEach找到的方法混淆了。

const foo = [3, 2, 1];
foo.forEach(item => {
    console.log(item);
});


推荐阅读