繁体   English   中英

(语法?)this.state不是函数错误和componentDidMount中的排序

[英](syntax?)this.state is not a function error & sorting in componentDidMount

我不断收到TypeError:this.state.pageOfItems不是一个函数,我无法理解,这可能是语法问题。 另外,我还有一个问题:我正在尝试使用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); }); 

this.state.pageOfItems是一个数组。 要遍历此数组,请执行以下操作:

this.state.pageOfItems.map(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>
   )
})

您可以在这里https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map阅读有关Array.map的信息。

您应该mapsortfilter ,而不是this.state.pageOfItems()

this.state.pageOfItems.map(item=>{})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM