[英]Having trouble sorting ul list items alphabetically (ascending/descending) in React.js
我是 React 的新手,所以这可能是一个非常愚蠢的问题,但我真的可以使用一些帮助! 我已经看遍了,我不明白为什么 sortList 函数什么都不做。 这是我的组件代码的开头:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [
{
id: 1,
text: 'bananas',
done: false
},
{
id: 2,
text: 'milk',
done: false
},
{
id: 3,
text: 'bread',
done: false
},
{
id: 4,
text: 'cheese',
done: false
}
],
text: "",
ascending: true
};
this.handleNewText = this.handleNewText.bind(this);
this.addItem = this.addItem.bind(this);
this.handleCheckOff = this.handleCheckOff.bind(this);
this.handleDeleteItem = this.handleDeleteItem.bind(this);
this.sortList = this.sortList.bind(this);
}
和不起作用的功能......
sortList() {
let newList = this.state.items.sort((a,b) => {
if (this.state.ascending) {
return a.text - b.text;
} else {
return b.text - a.text;
}
});
this.setState({
ascending: !this.state.ascending,
items: newList
});
}
和渲染功能...
render() {
return (
<div className="col-lg-6">
<form>
<input type="text" id="textBox" className="form-control" onChange={this.handleNewText} value={this.state.text} />
<button id="addButton" className="btn btn-primary" onClick={this.addItem} disabled={!this.state.text}>{"Add Item"}</button>
</form>
<div id="postIt">
<h1>Shopping List</h1>
<List items={this.state.items} onItemCheckedOff={this.handleCheckOff} onDeleteItem={this.handleDeleteItem} />
<button id="sortButton" className="btn btn-primary" onClick={this.sortList}>{"Sort"}</button>
</div>
</div>
);
}
}
除了 SortList 函数外,一切都很好。 我尝试了许多不同的方法,但无法使其正常工作。 发生最多的是列表项消失了!
您试图从彼此中减去 2 个字符串,从而返回 Nan。 排序需要 1 或 -1
let newList = this.state.items.sort((a, b) => {
if (this.state.ascending && a.text > b.text) {
return 1;
} else {
return -1;
}
});
希望这能回答你的问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.