【问题标题】:How to sort data in ascending or descending order in Reactjs?如何在 Reactjs 中按升序或降序对数据进行排序?
【发布时间】:2018-10-09 15:02:12
【问题描述】:

我在我的显示组件中导入了产品数据。对于 JSON 中的每个产品,我使用 .map() 来显示内容。现在我想按升序或降序对产品价格进行排序,但我做不到。

products.js:

 const products = [
  {
    "index": 0,
    "isSale": true,
    "isExclusive": false,
    "price": "Rs.2000",
    "productImage": "product-1.jpg",
    "productName": "Striped shirt",
    "size": ["XS", "S", "L", "XL"]
  },
  {
    "index": 1,
    "isSale": false,
    "isExclusive": false,
    "price": "Rs.1250",
    "productImage": "product-2.jpg",
    "productName": "Denim shirt",
    "size": ["XS", "S"]
  },
  {
    "index": 2,
    "isSale": false,
    "isExclusive": true,
    "price": "Rs.1299",
    "productImage": "product-3.jpg",
    "productName": "Plain cotton t-shirt",
    "size": ["S", "M"]
  },
  {
    "index": 3,
    "isSale": false,
    "isExclusive": false,
    "price": "Rs.1299",
    "productImage": "product-4.jpg",
    "productName": "Plain 3/4 sleeve cotton t-shirt",
    "size": ["XL"]
  },
  {
    "index": 4,
    "isSale": false,
    "isExclusive": false,
    "price": "Rs.2500",
    "productImage": "product-5.jpg",
    "productName": "White dress shirt",
    "size": ["M", "L"]
  },
  {
    "index": 5,
    "isSale": false,
    "isExclusive": false,
    "price": "Rs.2399",
    "productImage": "product-6.jpg",
    "productName": "Long Sleeve Skivvy Top",
    "size": ["XS", "S", "M"]
  },
  {
    "index": 6,
    "isSale": true,
    "isExclusive": false,
    "price": "Rs.2000",
    "productImage": "product-7.jpg",
    "productName": "Puffer Vest with Hood",
    "size": ["M", "L", "XL"]
  },
  {
    "index": 7,
    "isSale": false,
    "isExclusive": true,
    "price": "Rs.1699",
    "productImage": "product-8.jpg",
    "productName": "Funnel Neck Swing Top",
   "size": ["XS", "S", "XL"]
  }];

  export default products;

现在在显示组件中,我正在映射每个产品并显示它。

显示组件.js:

import React, { Component } from 'react';
import products from './products';

class App extends Component {

    constructor(){
        super();
        this.state = {
            sortDirection: 'descending',
            data: this.state.data.sort(descending)
        };
    }

    sortData() {
        if(this.state.sortDirection ==='descending') {
            this.setState({ 
                sortDirection: 'ascending',
                data: this.props.payYears.sort(sortAscending)
            });
        } else {
            this.setState({ 
                sortDirection: 'descending',
                data: this.props.payYears.sort(sortDescending)
            });
        }
    }

  render() {
    return (
      <div>
        <h1>This is display component</h1>

        <ul>
                {
                  products.map(product => {
                    return <li>{product.index} - {product.price}</li>;
                  })
                }
            </ul>

      </div>
    );
  }
}

export default App;

下面的屏幕截图显示了价格的初始顺序:

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

这样的东西应该是你要找的东西。

import React, { Component } from 'react';
import { render } from 'react-dom';
import products from './products';

class App extends Component {

  state = {
    products,
    prices: [],
  }

  componentDidMount() {
    const { products, prices} = this.state;

    prices = products.map(p => p.price.substr(3));
    this.setState({ prices })
  }

  sortAscending = () => {
    const { prices } = this.state;
    prices.sort((a, b) => a - b)    
    this.setState({ prices })
  }

  sortDescending = () => {
    const { prices } = this.state;
    prices.sort((a, b) => a - b).reverse()
    this.setState({ prices })
  }

  render() {
    const { prices } = this.state;
    return (
      <div>
        <ul>
          {
            prices.map((p, i) => {
              return <li>{i} - Rs.{p}</li>;
            })
          }
        </ul>
        <button onClick={this.sortAscending}>asc</button>
        <button onClick={this.sortDescending}>desc</button>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));

【讨论】:

    【解决方案2】:

    您没有展示排序功能的外观。我会这样定义它们:

    // a and b are single "product"
    
    const ascending = (a, b) => {
      const parsedA = parseInt(a.price.replace("Rs.", ""), 10);
      const parsedB = parseInt(b.price.replace("Rs.", ""), 10);
    
      return a - b;
    }
    
    const descending = (a, b) => {
      const parsedA = parseInt(a.price.replace("Rs.", ""), 10);
      const parsedB = parseInt(b.price.replace("Rs.", ""), 10);
    
      return b - a;
    }
    

    排序修改数组,所以你需要创建一个副本:

    sortData() {
        if(this.state.sortDirection ==='descending') {
            this.setState({ 
                sortDirection: 'ascending',
                data: this.props.payYears.slice().sort(sortAscending)
            });
        } else {
            this.setState({ 
                sortDirection: 'descending',
                data: this.props.payYears.slice().sort(sortDescending)
            });
        }
    }
    

    【讨论】:

      【解决方案3】:

      按价格升序排列数组-

            this.sortByPriceAsc=()=>{
      
                let sortedProductsAsc;
                sortedProductsAsc= this.state.products.sort((a,b)=>{
                   return parseInt(a.price)  - parseInt(b.price);
                })
      
                this.setState({
                    products:sortedProductsAsc
                })
            }
      

      按价格降序排列数组-

            this.sortByPriceDsc=()=>{
      
                let sortedProductsDsc;
                sortedProductsDsc= this.state.products.sort((a,b)=>{
                   return parseInt(b.price)  - parseInt(a.price);
                })
      
                this.setState({
                    products:sortedProductsDsc
                })
            }
      

      【讨论】:

        【解决方案4】:

        我们也可以使用函数式组件

        import React, { Component, useEffect, useState } from 'react';
        import products from './serveices.js';
        
        function Product() {
            const [prices, setPrices] = useState([])
        
            useEffect(() => {
                let prices = products.map(p => p.price.substring(3));
                setPrices(prices)
            }, []);
        
            const sortAscending = () => {
              const sortAscPrices = [...prices]
              sortAscPrices.sort((a, b) => a - b)    
              setPrices( sortAscPrices )
            }
            
            const sortDescending = () => {
                const sortDescPrices = [...prices]
                sortDescPrices.sort((a, b) => a - b).reverse()
                setPrices( sortDescPrices )
            }
        
            return (
              <div>
                <ul>
                  {
                    prices.map((p, i) => {
                      return <li>{i} - Rs.{p}</li>;
                    })
                  }
                </ul>
                <button onClick={sortAscending}>asc</button>
                <button onClick={sortDescending}>desc</button>
              </div>
            );
          }
        export default Product;
        

        感谢@Colin Ricardo 的课程组件

        【讨论】:

          猜你喜欢
          • 2018-05-03
          • 2017-06-10
          • 1970-01-01
          • 1970-01-01
          • 2023-03-07
          • 2013-09-10
          • 1970-01-01
          • 2020-11-09
          • 2019-07-17
          相关资源
          最近更新 更多