有人能详细解释或提供一个视频链接,帮助我了解如何在react中对mongodb进行排序吗



我看到了不同的版本,但老实说,它们毫无意义。我试着实现它们,这样我自己就能理解它,但我不知道应该把它放在哪里。它是放在我的view main.js文件中还是放在哪个文件中,然后放在那个文件的哪里。

import React, { useState, useEffect } from 'react'
import axios from 'axios'
import { Link } from '@reach/router'


const Main = props => {

const [pets, setPet] = useState()
useEffect((req, res) => {
axios.get(`http://localhost:8000/api/users`)
.then(res => {// does the sort go here
// console.log(res.data.users)
setPet(res.data.users)
})
}, [])
// would the sort go before or in here ? 

return (
<div>
These pets need a home:  do you know any other pets <a href="addpet"> Add Pet</a>
<table className='table table-striped table-dark '>
<thead className="">
<tr>
<th>Name</th>
<th>Type</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{
pets ?
pets.map((pet, i) => {
return (
<tr key={i}>
<td>{pet.pet_name}</td>
<td>{pet.pet_type}</td>
<td><Link to={`/viewpet/${pet._id}`}>Detail</Link> | <Link to={`/update/${pet._id}`}>Edit</Link></td>
</tr>
)
})
: ''
}
</tbody>
</table>
</div>
)
}
export default Main;

感谢@hellogoodnight和其他人的帮助,帮助我理解你在说什么。

答案是你说的:(

setPet(res.data.users.sort((a, b) => a.pet_name < b.pet_name ? -1 : 1)

最新更新