抱歉,我是 React 的新手,所以我遇到了一个问题,我的 Context 为其他组件提供了时间。当我仅将它与显示时钟的组件一起使用时,一切都很好。问题发生在另一个组件中,我想根据一天中的时间显示消息。太多的重新渲染。React 限制了渲染的数量以防止无限循环。
我的上下文组件
import React, { createContext, useState, useEffect } from "react";
import moment from "moment";
export const GreetingContext = createContext();
const getTime = () => {
return moment();
};
const GreetingContextProvider = (props) => {
const [currentTime, setCurrentTime] = useState(getTime);
const setTime = () => {
setInterval(() => {
setCurrentTime(getTime);
}, 1000);
return () => {
clearInterval(setTime);
};
};
useEffect(setTime, []);
return (
<GreetingContext.Provider value={currentTime}>
{props.children}
</GreetingContext.Provider>
);
};
export default GreetingContextProvider;
还有我的消息组件
import React, { useState, useContext} from "react";
import { useLocalStorage } from "../custome_hooks/useLocalStorage";
import { GreetingContext } from "../contexts/GreetingContext";
const Greeting = () => {
const time = useContext(GreetingContext);
const timeInHours = time.hours();
const [greeting, setGreeting] = useState("ooo");
const [name, setName] = useLocalStorage("name", "Your name");
// Setting the greeting depending on the time of the day
switch (true) {
case timeInHours > 0 && timeInHours < 5:
setGreeting("Good night");
break;
case timeInHours > 5 && timeInHours < 12:
setGreeting("Good morning");
break;
case timeInHours > 12 && timeInHours < 17:
setGreeting("Good day");
break;
case timeInHours > 17 && timeInHours < 24:
setGreeting("Good evening");
break;
default:
setGreeting("");
}
// Getting the name of the user
let handleChange = (e) => {
setName(e.target.value);
};
return (
<div className="greeting_container">
<h4>{greeting}</h4>
<input
type="text"
size={name.length + 1}
value={name}
onChange={handleChange}
/>
</div>
);
};
export default Greeting;
谢谢