如何对数据排序并在reactjs中显示?

时间:2018-12-27 05:48:31

标签: javascript reactjs

当用户单击按资金排序时,我想按排序方式显示项目,然后按资金排序时显示项目,但是我的代码不起作用,为什么?我正在导入sortBy()函数,并在用户单击按钮时使用它。

home.js:

import React, { Component } from 'react';
import Card from '../common/card';
import Projects from '../../data/projects';
import { sortBy } from './helper';

    export default class Home extends Component {

      constructor(props) {
        super(props);
        this.state = {
          projects: Projects
        }
      }

      render() {

        return (
          <div>
              <div className="header">
                <div className="buttonContainer">
                  <div>
                      <button className="btn btn-primary mycustom dropdown-toggle mr-4" type="button" data-toggle="dropdown" aria-haspopup="true"
                      aria-expanded="false">Sort by </button>

                      <div className="dropdown-menu">
                          <a className="dropdown-item" href="#" onClick={() => sortBy('funded')}>Percentage fund</a>
                          <a className="dropdown-item" href="#" onClick={() => sortBy('backers')}>Number of backers</a>
                      </div>
                  </div>
                </div>
              </div>
              <div class="container-fluid">
                <div class="row">
                  {this.state.projects.map( (val,index) => (
                    <div class="col-3">
                      <Card title={val.title} by={val.by} blurb={val.blurb} 
                      url={val.url} funded={val.funded} backers={val.backers} imgurl={index}/>
                    </div>
                  ))}
                </div>
              </div>
          </div>
        )
      }
    }

helper.js:

import projects from '../../data/projects';

export function sortBy (searchTerm) {
    if(searchTerm === 'funded'){
        return projects.sort((a,b) => a.funded - b.funded);
    }else if(searchTerm === 'backers'){
        return projects.sort((a,b) => a.backers - b.backers);
    }
}

projects.js:

http://jsfiddle.net/0z8xcf1o/

1 个答案:

答案 0 :(得分:2)

  1. 在渲染功能中,您应该遍历this.state.projects而不是Projects
  2. 您需要通过各种方式更新状态
  3. 您的sortBy函数可以简化,它应该为您设置状态,最好将其添加到组件中:

-

sortBy(searchTerm) {
  this.setState({ projects: [...Projects].sort((a, b) => a[searchTerm] - b[searchTerm]) });
}

然后用

调用
onClick={() => this.sortBy('funded')}