代码不是多好,只是一个方向,因为开发时间很少,现在也是抽出的时间写的这篇文章,意在后期复用快速完成功能。。。。
第一步,生成时间和月份
// y轴数据 (固定)
const times = ["07:00","08:00","09:00","10:00","11:00","12:00","13:00","14:00","15:00","16:00","17:00","18:00"]
const App = () => {
// x轴数据 (动态)
const [days, setDays] = useState(getDate(moment().format('YYYY-MM-DD')))
// 根据日期生成一周时间
function getDate (t) {
let base = new Date(t).getTime();
let oneDay = 24 * 3600 * 1000;
let date = [];
let data = [Math.random() * 300];
let time = new Date(base);
date.push(
`${
time.getMonth() + 1 > 9 ? time.getMonth() + 1 : "0" + (time.getMonth() + 1)
}-${time.getDate() > 9 ? time.getDate() : "0" + time.getDate()}`
);
for (let i = 1; i < 7; i++) {
let now = new Date((base += oneDay));
date.push(
`${
now.getMonth() + 1 > 9
? now.getMonth() + 1
: "0" + (now.getMonth() + 1)
}-${now.getDate() > 9 ? now.getDate() : "0" + now.getDate()}`
);
data.push(Math.round((Math.random() - 0.5) * 20 + data[i - 1]));
}
let newdate = date;
return newdate;
}
return ......
}
第二步根据时间和月份确定 一点
import { map } from "lodash";
const App = () => {
/**
* @param data 后端返回数据
* @param _date 当前查询的时间 (如: 2022-08-08)
*/
const handleData = (data, _date) = > {
let timeObj = {};
let result = [];
console.log("data", data);
map(times, (t, index) => {
timeObj = {
time: t, // y轴的时分
children2: [], // 根据x轴和y轴确定的点的数据
};
result.push(timeObj);
});
// 确定x轴
map(data, (d) => {
map(result, (r) => {
if (d.time.slice(0, 2) === r.time.slice(0, 2)) {
r.children2.push(d);
}
});
});
setBoardList(result);
}
}
大致逻辑是这样,实际使用可能还需要调整,因为需求变了多次,代码也是凭记忆写的,实际情况请根据项目调整