[英]How to sort Array Data in ReactJs
class LifeCycleComps extends Component { constructor(props) { super(props); this.state = { data: 0, names: [{ name: "sam" }, { name: "hammer" }, { name: "jellyfish" } ] }; //below is sortAlphabet function sortAlphabet = () => { this.setState({ names: this.state.names.sort() }); }; //sortNames component class SortNames extends Component { render() { return <span > { this.props.names.name } < /span>; } }
<button onClick={this.sortAlphabet}>sort</button> <ul> {this.state.names.map((item, i) => ( <SortNames key={i} names={item} /> ))} </ul>
以上是我的代碼。 我不確定主要問題是什么。 在上面的代碼中,我想通過onClick
獲得排序的名稱。 但是我沒有從上面的片段中得到任何積極的結果。 請讓我知道人們我做錯了什么?
您不能直接在對象數組中使用排序函數。 為此,您需要編寫一個排序函數或編寫一個回調函數,您可以根據需要進行修改。 這是工作代碼( https://stackblitz.com/edit/react-31un7h ):
import React, { Component } from 'react';
import { render } from 'react-dom';
const SortNames = (props) => {
return (
<span >
{props.names.name}
</span>
)
}
class LifeCycleComps extends Component {
constructor(props) {
super(props);
this.state = {
data: 0,
names: [{
name: "sam"
},
{
name: "hammer"
},
{
name: "jellyfish"
}
]
};
}
compare = ( a, b ) => {
if ( a.name < b.name ){
return -1;
}
if ( a.name > b.name ){
return 1;
}
return 0;
}
//below is sortAlphabet function
sortAlphabet = () => {
this.setState({
names: this.state.names.sort(this.compare)
});
};
render(){
return (
<div>
<button onClick={this.sortAlphabet}>sort</button>
<ul>
{this.state.names.map((item, i) => (
<SortNames key={i} names={item} /> ))}
</ul>
</div>
);
}
}
//sortNames component
class App extends Component {
constructor() {
super();
this.state = {
name: 'React'
};
}
render() {
return (
<div>
<LifeCycleComps/>
</div>
);
}
}
render(<App />, document.getElementById('root'));
這是排序值
let arr = [{ name: "sam" }, { name: "hammer" }, { name: "jellyfish" }] function sortIt(x,y) { if ( x.name < y.name ){ return -1; } if ( x.name > y.name ){ return 1; } return 0; } arr.sort(sortIt); console.log(arr);
這是在 reactjs
sortIt(x,y) {
if ( x.name < y.name ){
return -1;
}
if ( x.name > y.name ){
return 1;
}
return 0;
}
sortAlphabet = () => {
this.state.names.sort(this.sortIt)
this.setState({
names: this.state.names.sort()
});
};
render() {
return (
<>
<button onClick={this.sortAlphabet}>sort</button>
<ul>
{this.state.names.map((item, i) => (
<li key={i} names={item}>{item.name}</li> ))}
</ul>
</>
);
它只是調整下面評論中提供的javascript代碼。
compare = ( a, b ) => {
if ( a.name < b.name ){
return -1;
}
if ( a.name > b.name ){
return 1;
}
return 0;
}
//below is sortAlphabet function
sortAlphabet = () => {
let objs = [...this.state.names] //create a copy here as you will not want to directly mutate the state by calling sort.
this.setState({
names: objs.sort( compare );
});
};
我制作了一個StackBlitz ,您可以在其中看到解決方案。 希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.