gpt4 book ai didi

javascript - 从 react 应用程序的下拉列表中选择选项时按字母顺序对对象数组进行排序

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

我正在尝试根据标题和导演进行排序,但只有下拉列表中的第二个选项始终有效。下面是我的代码。仅选择第二个选项(可能是 asc 或 desc)时,将执行排序

class App extends Component {
constructor() {
super();
this.state = {
movies: data.movies, sort_term: '',
};
this.onSorting = this.onSorting.bind(this);
}
onSorting(e) {
let term = 'Title';
let option = e.target.value;
let sortedList = [...this.state.movies].sort((a, b) => {
return (option == 'asc' ? (a[term] <= b[term] ? -1 : 1) :
(a[term] >= b[term] ? -1 : 1))
});
this.setState({ sort_term: term });
this.setState({ movies: sortedList });
}

render() {
return (
<div>
<Hello sort_term={this.state.sort_term}
onSorting={this.onSorting} />
<br />
<Table movies={this.state.movies} />
</div>
);
}
}

Hello.js

class Hello extends Component {
render() {
const { sort_term, onSorting } = this.props;
return (
<div className="header">
Database
<ul className="navLeft">
<li >
<form >
<select value={sort_term}
onChange={onSorting}
className="searchBar">
<option value="desc">Sort Title(Z - A)</option>
<option value="asc">Sort Title(A - Z)</option>
</select>
</form>
</li>
</ul>
</div>
);
}
}

最佳答案

我建议您像这样定义“OnSorting”函数

class App extends Component {
constructor() {
super();
this.state = {
movies: data.movies,
sort_term: '',
};
}

onSorting = (e) => {
let term = 'Title';
let option = e.target.value;
let sortedList = [...this.state.movies].sort((a, b) => {
return (option == 'asc_Title' ? (a[term] >= b[term] ? -1 : 1) :
(a[term] <= b[term] ? -1 : 1))
});
this.setState({ sort_term: term });
this.setState({ movies: sortedList });
}

render() {
return (
<div>
<Hello sort_term={this.state.sort_term}
onSorting={this.onSorting} />
<br />
<Table movies={this.state.movies} />
</div>
);
}
}

//Hello.js

class Hello extends Component {
render() {
const { sort_term, onSorting } = this.props;
return (
<div className="header">
Database
<ul className="navLeft">
<li >
<form >
<select
onChange={onSorting}
className="searchBar">
<option value="desc">Sort Title(Z - A)</option>
<option value="asc">Sort Title(A - Z)</option>
</select>
</form>
</li>
</ul>
</div>
);
}
}

关于javascript - 从 react 应用程序的下拉列表中选择选项时按字母顺序对对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52050058/

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