gpt4 book ai didi

javascript - 如何在reactjs中对数据进行排序并显示?

转载 作者:行者123 更新时间:2023-12-01 01:24:22 25 4
gpt4 key购买 nike

当用户单击按资金排序时,我想以排序的方式显示项目,那么它应该以按资金排序的方式显示项目,但我的代码无法正常工作,为什么会这样?我正在导入 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. 在渲染函数中,您应该迭代 this.state.projects 而不是 Projects
  2. 您需要在每次排序时更新您的状态
  3. 您的 sortBy 函数可以简化,它应该为您设置状态,并且最好将其添加到组件中:

-

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

然后用

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

关于javascript - 如何在reactjs中对数据进行排序并显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53940299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com