this.props.playedGames从我的Redux状态中提取,并从最近日期排序到第一个条目(降序)。我需要我的累积折线图(chart.js)的数据顺序与最近日期的第一个条目的顺序相反。我如何在不使用每次刷新时不断反转的反转方法的情况下做到这一点。我不想重新调用API,因为我有我需要的数据。
我已经尝试为页面刷新时创建一个状态,这样它就不会刷新。我已经尝试了几种不同的方法。所有操作都失败了。
我的代码:
import { connect } from 'react-redux';
import {withRouter} from 'react-router';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';
import {Line} from 'react-chartjs-2';
class ChartPage extends Component {
profitForChart = (props) => {
let total = 0
return this.props.playedGames.reverse().map( (game, index) => ({
x: index,
y: total += parseFloat(game.profit)
}))
}
render() {
if(!this.props.playedGames) return <h1>Loading...</h1>
const { classes } = this.props;
const data = {
datasets: [{
data: this.profitForChart(),
label: 'PROFIT'
}],
labels: this.props.playedGames.map( game => (new Date(game.start_date_time)).toLocaleDateString()),
}
return(
<div className={classes.root}
<Line data={data} />
</div>
)
}
}
const mapStateToProps = ( state ) => {
return {
playedGames: state.userPlayedGames.playedGames,
isLoading: state.isLoading,
}
}
const mapDispatchToProps = {
}
ChartPage.propTypes = {
classes: PropTypes.object.isRequired,
};
export default compose(
withStyles(styles, {
name: 'ChartPage',
}),
connect(mapStateToProps, mapDispatchToProps))(withRouter(ChartPage));
预期结果:2018年1月、2018年2月、2018年3月,累积折线图随着时间的推移而上升。
实际结果:(在初始加载和每次刷新时是正确的),但下一个是错误的:图形累积是反向的,日期向后: 3/2018,2/2018,1/2018。
发布于 2019-02-07 12:25:37
假设api给出以下响应,
const response = [{x: 3, y: 5, date: '1/2/2018'}, {x: 3, y: 5, date: '1/4/2019'}, {x: 3, y: 5, date: '1/4/2013'}, {x: 3, y: 5, date: '1/2/2016'}]
现在,我们可以使用排序函数按日期对其进行排序。
response
.sort((a,b) => new Date(a.date) > new Date(b.date) ? -1 : 0)
.map(// use your above code)
发布于 2019-02-07 12:39:34
reverse()
(也叫sort()
)是一个就地函数,这意味着它会修改调用它的数组的内容。它与react的不变思想背道而驰,即数据在创建后不能更改。
我建议您在将数组传递到组件的props之前克隆数组(并反转克隆的数组):
const mapStateToProps = ( state ) => {
return {
playedGames: state.userPlayedGames.playedGames.slice().reverse(),
isLoading: state.isLoading,
}
}
发布于 2019-02-07 13:34:34
你可以使用static getDerivedStateFromProps(props, state)
生命周期方法来反转你的“playedGames”,而不是在每次刷新时反转。
static getDerivedStateFromProps(props, state) {
// Any time the playedGames changes,
// Reverse and store in the state
if (props.playedGames !== state.playedGames) {
const dataForChart = props.playedGames.reverse().map((game, index) => ({
x: index,
y: (total += parseFloat(game.profit)),
}));
return {
dataForChart: dataForChart,
playedGames: playedGames,
};
}
return null;
}
然后使用状态中的排序数据来绘制图形。(this.state.dataForChart
)
https://stackoverflow.com/questions/54565939
复制相似问题