我想要實作的功能是 React 組件根據資料陣列中資料的時間戳顯示將要發生的任務。
陣列的每個元素都有兩個時間戳,任務開始的時間戳和任務完成的時間戳。
但是,不幸的是我不知道如何讓組件動態顯示將要執行的任務。
也就是說,如果有任務要執行,則顯示正在啟動的任務,否則不顯示該任務,等待陣列中的下一個任務啟動后才能顯示。
我希望我沒有被迷惑??
import React, { useEffect, useState } from 'react'
const data = [
{
id: 1,
title: "Read book"
start: "2021-12-30T14:41:39 0000",
end: "2021-12-30T15:41:39 0000"
},
{
id: 2,
title: "Clean desk"
start: "2021-12-30T17:01:39 0000",
end: "2021-12-30T17:24:39 0000"
}
]
const App = () => {
const [currentTask, setCurrentTask] = useState(undefined)
useEffect(() => {
setCurrentTask(getCurrentTask())
}, [currentTask])
const getCurrentTask = () => {
return data ? data.find((task) => new Date(data.start).getTime() <= Date.now()) : undefined
}
return (
<>
{currentTask ? <div>{currentTask.title}</div> : <div>No current task</div>}
</>
)
}
我怎么能實作這個???
uj5u.com熱心網友回復:
您可以通過使用 setInterval 或useInterval定期檢查資料并根據開始日期時間更新狀態來完成此操作,我將庫中的 useInterval 代碼放在此處以查看如何在反應中正確使用 setInterval :
使用間隔:
import React, { useEffect, useRef, useLayoutEffect } from "react";
export function useInterval(callback, delay) {
const savedCallback = useRef(callback);
useLayoutEffect(() => {
savedCallback.current = callback;
}, [callback]);
useEffect(() => {
if (!delay && delay !== 0) {
return;
}
const id = setInterval(() => savedCallback.current(), delay);
return () => clearInterval(id);
}, [delay]);
}
應用組件:
import React, {useState} from "react";
import useInterval from "./useInterval";
const data = [
{
id: 1,
title: "Read book",
start: "2021-12-30T19:33:20",
end: "2021-12-30T19:20:20",
},
{
id: 2,
title: "Clean desk",
start: "2021-12-30T19:31:39",
end: "2021-12-30T19:25:39",
},
];
const App = () => {
const [currentTask, setCurrentTask] = useState(undefined);
useInterval(
() => {
const currentTask = getCurrentTask();
setCurrentTask(currentTask);
},
// Delay in milliseconds or null to stop it
60000
);
const getCurrentTask = () => {
return data
? data.find((task) => {
const startTime = new Date(task.start).getTime();
const endTime = new Date(task.end).getTime();
const now = Date.now();
return startTime <= now && endTime >= now;
})
: undefined;
};
return (
<>
{currentTask ? (
<div>{currentTask.title}</div>
) : (
<div>No current task</div>
)}
</>
);
};
export default App;
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/398178.html
標籤:javascript 反应 反应原生
下一篇:根據不同的環境設定自定義標頭
