[英]Sort breaking on subsequent render in React JS components
I have an array closedPeriods
that looks like this: 我有一个closedPeriods
数组,看起来像这样:
this.state = {
selectedPortfolio: "",
selectedPeriod: "",
closedPeriods= [
{ portfolio: "foo", period: "june 2017", periodStart: "2017-06-01 00:00:00.000" },
{ portfolio: "foo", period: "may 2017", periodStart: "2017-05-01 00:00:00.000" },
{ portfolio: "bar", period: "may 2017", periodStart: "2017-05-01 00:00:00.000" }
]
}
I have a dropdown that selects the portfolio, then with the portfolio hand, I am rendering the period. 我有一个下拉菜单,可以选择投资组合,然后用投资组合的手绘制周期。
Filter state array by portfolio 按组合过滤状态数组
let periodByPortfolio = [];
if(this.state.selectedPortfolio) {
periodByPortfolio = this.state.closedPeriods
.filter(item => item.portfolio === this.state.selectedPortfolio);
}
Render periods belonging to portfolio: 属于投资组合的渲染期:
<label>Closed Periods</label>
<select id="closedPeriods">
{periodByPortfolio.sort((previous, current) => current.periodStart - previous.periodStart)
.map(option => {
return (<option key={option.period} value={option.period}>{option.period}</option>);
})}
</select>
TLDR: My sorting function works on the first render. TLDR:我的排序功能适用于第一个渲染。 As soon as I change Portfolio, and change back to the selected portfolio, my sorting becomes scrambled. 一旦更改投资组合,然后又回到选定的投资组合,我的排序就会变得混乱。 Why? 为什么?
EDIT 编辑
Sorting issue was caused by one of the functions double-binding to the component. 排序问题是由与组件双重绑定的功能之一引起的。
// Bind 1
constructor() {
this.filterOption = this.filterOption.bind(this);
}
// Bind 2
<select id="portfolio" value={this.props.portfolio} onChange={this.filterOption.bind(this, "portfolio")}>
Solution in Answer. 解决方案。
The solution is to remove the second bind. 解决方法是删除第二个绑定。 Also, you don't have to feed the function a target. 另外,您不必向函数提供目标。 You can use the event object to handle the name
part. 您可以使用事件对象来处理name
部分。
From 从
<select id="portfolio" value={this.props.portfolio} onChange={this.filterOption.bind(this, "portfolio")}>
To 至
<select id="portfolio" name="selectedPortfolio" value={this.props.portfolio} onChange={this.filterOption}>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.