在我的React应用程序中,我想按字母顺序对数据进行排序,并根据从高到低的整体分数进行排序
渲染组件时,将根据2个json文件中的数据计算总分
我添加了一个字母排序。
为简单起见,在下面的示例中,我只对一个配置文件进行了排序。
问题:
// my files.json
let profiles = {"name": "Will", "skillset" : {"a": 3, "b": 2}}
let disciplines = [
{"name": "Diving", "requirements" : {"a": 2, "b": 5}},
{"name": "Tennis", "requirements" : {"a": 3, "b": 1}},
{"name": "BMX", "requirements" : {"a": 4, "b": 2}},
]
const disciplineScore = (profileSkillset, disciplineRequirements) => {
let score = 20
for (let skill of Object.keys(profileSkillset))
score = score + (profileSkillset[skill] + disciplineRequirements[skill])
return score
}
class Main extends React.Component {
constructor(props) {
super(props);
this.state = { data: this.props.disciplines }
this.sortBy = this.sortBy.bind(this)
}
compareBy(key) {
return function (a, b) {
if (a[key] < b[key]) return -1
if (a[key] > b[key]) return 1
return 0
}
}
sortBy(key) {
let arrayCopy = [...this.state.data]
arrayCopy.sort(this.compareBy(key))
this.setState({ data: arrayCopy })
}
render() {
let { data } = this.state
const disciplineList = data.map((discipline) => {
return (
<div key={discipline.name}>
<span className='name' >{discipline.name}</span> - <span className='score'>
{disciplineScore(this.props.profiles.skillset, discipline.requirements)}
</span>
</div>
)
})
return (
<section>
<div className='sort-wrap'>
<button onClick={() => this.sortBy('name')}>Sort A to Z</button>
<button onClick={() => this.sortBy()}>Sort high to low</button>
</div>
<div className='content'>
{ disciplineList }
</div>
</section>
)
}
}
const App = () => (
<div><Main profiles={profiles} disciplines={disciplines} /></div>
)
ReactDOM.render(
<App />,
document.getElementById('root')
)
button {
margin: 10px;
}
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>
答案 0 :(得分:0)
你的州应该是:
this.state = { data: this.props.disciplines, sort: sort }
排序可以是一个关键,一个功能,无论你喜欢什么
重点是,我们可以单独更改this.state.data
和this.state.sort
,我们在更改值时不会重新排序。
我们在渲染时排序
或者,不要排序以获得原始订单。