我有一个选择,它从 api 获取选项,它看起来像这样:
我想按升序对它们进行排序,但我不知道该怎么做,这是我的代码
<select className="form-control form-control-sm" name="subscriptions" onChange={this.changeValues}>
{
this.state.variantsData.subscription_plans.map((item, i) => <option key={i} value={item.uuid}>{item.name}</option>)
}
</select>
最佳答案
您可以编写一个函数来对数据进行排序,然后可以渲染该数据。要进一步优化它,您可以memoize
这个函数
sortData = (array) => {
return array.sort(function(a, b) {
a.match(/(\d+) months/i)[1] - b.match(/(\d+) months/i)[1]
})
}
render() {
const data = this.sortData(this.state.variantsData.subscription_plan);
return (
<select className="form-control form-control-sm" name="subscriptions" onChange={this.changeValues}>
{this.state.variantsData.subscription_plans.map((item, i) => (
<option key={i} value={item.uuid}>{item.name}</option>
))
}
</select>
)
}
关于javascript - ReactJS:从 API 中排序选项选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53084318/