1 回答
TA贡献1816条经验 获得超4个赞
您的 if-else 逻辑不会为您提供正确的标头,并且您正在将它们压扁在 top-level 上else。你得到正确的标题
let listHeader = "--";
if (time === "none") {
if (hour) {
setTime("hour");
} else if (day) {
setTime("day");
} else {
setTime("older");
}
} else {
if (hour) {
listHeader = "Last Hour";
} else if (day) {
listHeader = "Today";
} else {
listHeader = "Older";
}
}
您没有对标头中的内容进行分组,因此返回它的方式并不是您想要的。以下代码是有关如何执行此操作的示例
import React from "react";
import "./App.css";
const useLoadData = () => {
const data = [
{id: "01", content: "content 1", time: "3 seconds ago"},
{id: "02", content: "content 2", time: "4 minutes ago"},
{id: "03", content: "content 3", time: "35 minutes ago"},
{id: "04", content: "content 4", time: "3 hours ago"},
{id: "05", content: "content 5", time: "4 days ago"}
];
//item 1 should get a heading "Last hour"
//item 2 and item 3 should not get a heading. They are also under "Last hour"
//item 4 should get a heading "Today"
return data;
};
function findListHeader(item) {
let timeC = item.time
let listHeader = "--";
let hour = false;
let day = false;
if (timeC.includes("second") || timeC.includes("minute")) {
hour = true;
}
if (timeC.includes("hour")) {
day = true;
}
if (hour) {
listHeader = "Last Hour";
} else if (day) {
listHeader = "Today";
} else {
listHeader = "Older";
}
return {header: listHeader, item};
}
export default function App() {
const var1 = useLoadData();
let headers = ["Last Hour", "Today", "Older"]
const itemHeaders = var1.map((itemP) => findListHeader(itemP));
const var2 = headers.map((header) =>
<CommentOne
key={header}
header={header}
items={itemHeaders
.filter(itemWithHeader => itemWithHeader.header === header)
.map(itemWithHeader => itemWithHeader.item)
}
/>);
return <div> {var2} </div>;
}
function CommentOne({header, items}) {
let content = items.map(item => <p>{item.content}</p>)
return (
<div className="App">
<h1>{header}</h1>
{content}
</div>
);
}
添加回答
举报