我正在建立一个返回其ID,缩略图,标题,剧集编号和发行日期的电影网格。
如何映射reorderByDate()和reorderByEpisode()方法以获得退货重新订购值?
CodeSandbox Demo和Api Documentation Swapi
Films.js组件:
import React, { Component } from 'react';
import axios from 'axios';
import ListFilms from './ListFilms'
class Films extends Component {
constructor(props) {
super(props);
this.state = {
films: [],
}
this.getFilms = this.getFilms.bind(this)
}
getFilms() {
return axios.get('https://swapi.co/api/films')
...
})
}
reorderByDate = () => {
let films = this.state.films.map(item => ({ ...item }));
films.sort((a, b) =>
a.release_date > b.release_date
? 1
: b.release_date > a.release_date
? -1
: 0
);
this.setState({ films });
};
reorderByEpisode = () => {
let films = this.state.films.map(item => ({ ...item }));
films.sort((a, b) =>
a.episode_id > b.episode_id ? 1 : b.episode_id > a.episode_id ? -1 : 0
);
this.setState({ films });
};
componentWillMount(){
this.getFilms();
}
render() {
const { films } = this.state;
return(
<div className="container">
<div className="d-flex justify-content-center align-items-center mb-2">
<p className="mb-0 mr-2">Filter by:</p>
<button onClick={this.reorderByDate} type="button" className="btn btn-warning btn-sm">Released Date</button>
<p className="mb-0 mx-2">or:</p>
<button onClick={this.reorderByEpisode} type="button" className="btn btn-warning btn-sm">Episode Number</button>
</div>
<ListFilms films={films} />
</div>
)
}
};
export default Films;
答案 0 :(得分:0)
要解决当前情况,可以在按钮上使用onClick()
侦听器,并使用箭头运算符或将函数绑定到this
在函数内,使用Array.prototype.sort
方法来实现用于根据日期或剧集编号进行排序的自定义逻辑
引用https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
您应使用this.setState(prevState => nextState)
函数语法,因为您试图将电影数组从现有的状态对象更新为已排序的数组并重新渲染
答案 1 :(得分:0)
请使用https://codesandbox.io/s/zn923169mx
中更新的代码reorderByDate = () => {
let films = this.state.films;
// let films = this.state.films;
//console.log("from real",films[0].release_date);
films = films.sort((a, b) => {
let date1 = new Date(a.release_date).getTime();
let date2 = new Date(b.release_date).getTime();
console.log(date1);
return date1 - date2;
});
this.setState({ films });
};
reorderByEpisode = () => {
// console.log(...films.episode_id);
let films = this.state.films;
films = films.sort(function(a, b) {
return a.episode_id - b.episode_id;
});
this.setState({ films });
};
答案 2 :(得分:-1)
这里是按release_date
对电影进行排序的示例。这是您可以在其他基础上进行排序的基本思想。将renderByDate()
添加到Films
和Films
容器中的按钮以调用方法
//add this button in your `Films` component
<button onClick={this.renderByDate}>Render By Date</button>
renderByDate = () => {
let films = this.state.films;
//console.log("from real",films[0].release_date);
films = films.sort((a, b) => {
let date1 = new Date(a.release_date).getTime()
let date2 = new Date(b.release_date).getTime()
console.log(date1);
return date1 - date2;
});
this.setState({ films });
};