gpt4 book ai didi

javascript - 无法对 react 中的对象数组进行排序

转载 作者:行者123 更新时间:2023-11-30 09:17:51 26 4
gpt4 key购买 nike

我试图在按下按钮时按字母顺序对数组进行排序,但到目前为止我尝试的所有操作都失败了。当我尝试控制台记录某些内容并在控制台中打印时,按钮和功能起作用。我觉得我的排序功能有问题,但我不确定该怎么做。我该如何解决这个问题才能正常工作?

import React from "react";
import './Brewery.css'
import { Link } from 'react-router-dom';
import { ButtonToolbar, DropdownButton, MenuItem } from 'react-bootstrap';


class Brewery extends React.Component {
constructor(props) {
super(props);
this.state = {
showMenu: false,
breweries: []
}
}

componentDidMount() {
fetch("https://api.openbrewerydb.org/breweries")
.then(response => response.json())
.then((data) => {
this.setState({
breweries: data,
})
})
}

sortAlpha() {
const breweries = [].concat(this.state.breweries)
.sort((a, b) => a.name > b.name)
this.setState({breweries:breweries});
}

render() {

const { breweries } = this.state;

return(
<div className="main-container">
<div className="banner" styles="background-image: linear-gradient(-225deg, rgba(0,101,168,0.6) 0%, rgba(0,36,61,0.6) 50%), url('http://bitterminnesotabrewerytours.com/wp-content/uploads/2014/02/boston-beer-tours-glass.jpg');">
<div className="banner-content">
<h1>Brewery</h1>
<p>Find the best brewery in town</p>
</div>
</div>
<div className="container">
<div>
<button onClick={() => this.sortAlpha()}>Sort Alphabetically</button>
</div>
<div className="row">
{breweries.slice(0,10).map((brewery, i) =>
<div className="col-xs-12 col-sm-4" key={i}>
<Link to={`/brewery/${ brewery.id }`}>
<div className="card">
<div className="card-description">
<h2>{brewery.brewery_type}</h2>
<p>{brewery.city}, {brewery.state}</p>
</div>
<div className="card-category"><img src="https://img.icons8.com/color/20/000000/beer.png"/> {brewery.name}</div>
</div>
</Link>
</div>
)}
</div>
</div>
</div>
)
}
}

export default Brewery;

最佳答案

试试这个

sortAlpha() {
const breweries = [...this.state.breweries].sort((a, b) => {
if (a.name < b.name) return -1;
if (a.name > b.name) return 1;
return 0;
});
this.setState({ breweries: breweries });
}

关于javascript - 无法对 react 中的对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53821428/

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