我正在尝试根据标题和导演进行排序,但是下拉菜单中的第二个选项始终有效。这是下面的代码。在仅选择第二个选项(可能是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>
);
}
}
答案 0 :(得分:1)
我建议您像这样定义“ 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>
);
}
}