[英]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.