我创建了两个按钮,用于对列表的年份字段进行升序和降序排序。它们工作得很好。然后我想用一个切换按钮来替换按钮在升序和降序之间切换。这行不通。我的代码如下。有人能指点一下吗?非常感谢。
import { useEffect, useState } from 'react';
import {Button} from "reactstrap";
const MovieList = () => {
const [movies, setMovies] = useState([])
const [sort, setSort] = useState(true)
// Sort by Year
// I need to use localeCompare because the year is string
const sortByYearDesc = () => {
const sorted = [...movies].sort((a, b) => {
return b.year.localeCompare(a.year);
});
setMovies(sorted);
}
const sortByYearAsc = () => {
const sorted = [...movies].sort((a, b) => {
return a.year.localeCompare(b.year);
});
setMovies(sorted);
}
const toggleSort = () => {
setSort(!sort)
return sort ? sortByYearAsc : sortByYearDesc
}
return (
<div className="container">
<h1>Movies</h1>
<hr />
<div>
<Button onClick={toggleSort} color="info">{sort ? "Sort by Desc" : "Sort by Asc"}</Button>
</div>
<div>
<table className="table table-bordered table-striped">
<thead className="thead-dark">
<tr>
<th>Year</th>
<th>Film Name</th>
<th>Oscar Winner</th>
<th>Country</th>
</tr>
</thead>
<tbody>
{movies.map(movie => (
<tr key={movie.id}>
<td>{movie.year}</td>
<td>{movie.filmName}</td>
<td>{movie.winner}</td>
<td>{movie.country}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)
}
export default MovieList;
由于sortByYearAsc
和sortByYearDesc
是函数,因此需要在toggleSort
函数中执行。
。updated code
将为
const toggleSort = () => {
setSort(prevSort => !prevSort)
!sort ? sortByYearAsc() : sortByYearDesc() // since the state is not updated yet.
}
选项2
你也可以使用useEffect
钩子,当sort
更新时,useEffect
将执行相关的函数。
只更新toggleSort
const toggleSort = () => {
setSort(prevSort => !prevSort)
}
然后根据sort
的变化使用useEffect
useEffect(() => {
sort ? sortByYearAsc() : sortByYearDesc()
}, [sort])