Javascript 按出生月份将api中的用户排序为块
js初学者。 有这样的任务。不幸的是,在从api导入用户后,我被卡住了Javascript 按出生月份将api中的用户排序为块,javascript,reactjs,Javascript,Reactjs,js初学者。 有这样的任务。不幸的是,在从api导入用户后,我被卡住了 function App() { const [users, setUser] = useState(null); const fetchData = async () => { const response = await axios.get( 'https://....api.users' ); setUser(response.data); };
function App() {
const [users, setUser] = useState(null);
const fetchData = async () => {
const response = await axios.get(
'https://....api.users'
);
setUser(response.data);
};
return (
<div className="App">
<h1>Users list</h1>
<div>
<br />
</div>
<div className="users">
{users &&
users.map((user, index) => {
const cleanedDate = new Date(user.released).toDateString();
const name = user.firstName;
return (
<div className="user" key={index}>
<h3>user {index + 1}</h3>
<h2>{user.name}</h2>
<div className="details">
<p>First problem to solve is to get month from еру date of birth.
It can be achieved this way (+1 needed because month count starts from zero):
var date = new Date(user.released)
var month = date.getMonth() + 1
函数应用程序(){
const[users,setUser]=useState(null);
const fetchData=async()=>{
const response=等待axios.get(
'https://....api.users'
);
setUser(response.data);
};
返回(
用户列表
{用户&&
users.map((用户,索引)=>{
const cleanedDate=新日期(user.released).toDateString();
const name=user.firstName;
返回(
用户{index+1}
{user.name}
首先要解决的问题是从出生日期算起的月份。
可以通过这种方式实现(+1,因为月份计数从零开始):
然后,您必须将您的用户数组转换为dictionary,其中,键是month number,值是user本身
let usersByMonth = {};
for(let i=0; i<users.length; i++) {
const monthNumber = new Date(user.released).getMonth() + 1;
usersByMonth[monthNumber] = user;
}
Reduce的工作原理与
return (
<div className="january">usersByMonth["1"].map...</div>
<div className="february">usersByMonth["2"].map...</div>
...
)
让usersByMonth={};
for(让i=0;它有很多!现在我有了这样的smthng,这里有一个新的麻烦:要完成第3段,请根据本月出生的人数更改月份块的颜色。4)当鼠标悬停在月份块上时,显示本月出生的人的列表。),我需要为一个月的数组编写一个if-else函数,但是我遇到了错误(例如:谢谢您的时间!
return (
<div className="january">usersByMonth["1"].map...</div>
<div className="february">usersByMonth["2"].map...</div>
...
)