gpt4 book ai didi

javascript - Reactjs - 使用功能组件启动应用程序时调用函数

转载 作者:行者123 更新时间:2023-12-05 04:59:16 25 4
gpt4 key购买 nike

我的应用程序会根据一天中的不同时间显示诸如“早上好” 之类的问候语。我有一个功能可以检查时间并根据现在的时间更改问候语。我不能使用 componentDidMount,因为它是一个功能组件,所以我正在使用 React.useEffect。问题是这不会在启动时运行,应用程序显示“早上好”然后将更改为 “下午好” 时会有一小段延迟。我怎样才能消除这种延迟。

根据时间判断问候语的函数

const [currGreeting, setCurrGreeting] = useState(greetings[0]);

//Involves saving to localStorage so the transition can be seamless if the app is exited and returned to

function updateGreeting(){
time = new Date();

let hour = time.getHours();

console.log(hour);

if(12 > hour && hour > 5){
setCurrGreeting(greetings[0]);
console.log("Good Morning")

const curSessionGreeting = JSON.parse(localStorage.getItem("sessionGreeting")) || [];
if(curSessionGreeting != currGreeting){
localStorage.setItem("sessionGreeting", JSON.stringify(greetings[0]));
setCurrGreeting(greetings[0]);
}
}
if((18 > hour && hour > 12) || hour === 12){
setCurrGreeting(greetings[1]);
console.log("Good Afternoon")

const curSessionGreeting = JSON.parse(localStorage.getItem("sessionGreeting")) || [];
if(curSessionGreeting != currGreeting){
localStorage.setItem("sessionGreeting", JSON.stringify(greetings[1]));
setCurrGreeting(greetings[1]);
}
}
if(hour > 18 || (5 > hour && hour > 0)){
setCurrGreeting(greetings[2]);
console.log("Good Evening")

const curSessionGreeting = JSON.parse(localStorage.getItem("sessionGreeting")) || [];
if(curSessionGreeting != currGreeting){
localStorage.setItem("sessionGreeting", JSON.stringify(greetings[2]));
setCurrGreeting(greetings[2]);
}
}
}

更新问候语

React.useEffect(() => {
setInterval(()=>updateGreeting(), 1000);
});

应用呈现的位置

return (
<div>
<div style = {{display: 'flex', fontFamily: 'Work Sans', fontSize: 25,marginBottom: 25, color: '#CDCACA'}}>
<text>{currGreeting}</text>
</div>
</div>
);
};

export default App;

最佳答案

您应该在执行 setInterval 之前运行一个 updateGreeting,因为这会延迟第一次 updateGreeting 执行一秒 1000ms异步执行:


React.useEffect(() => {

updateGreeting()//first execution

setInterval(()=>updateGreeting(), 1000);
},[]);

关于javascript - Reactjs - 使用功能组件启动应用程序时调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63605682/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com