当 if 条件为真时,用 useEffect 编写的函数打印一个值两次。任何人都可以帮我解决吗?

A function written in useEffect printing a value twice when the if condition got true. Can anyone help me to solve it?

const fetchNotes = async () => {
    try {
      let res = await axios.get("/api/notes", config);
      setNotes(res.data);
      // console.log(notes); 
    } catch (err) {
      setError(err.response.res);
    }
  };

注意:我已经删除了React.StrictMode

将此 return 语句添加到您的 useEffect 函数中,您会没事的:

useEffect(() => {
        function checkReminder() {
            let remind = 0;
            let currentDate = new Date();
            let currentDateSec = Math.floor(currentDate.getTime() / 1000);

            for (let index = 0; index < notes.length; index++) {
                remind = notes[index].reminderTime;
                let msgTime = remind - currentDateSec;
                console.log(msgTime);

                if (msgTime === 0) {
                    console.log("hi");
                    clearInterval(interval);
                }
            }
        }
        const interval = setInterval(() => {
            checkReminder();
        }, 1000);

        return () => {
            clearInterval(interval);
        };
    })

有时需要 return 来自 useEffect 的清理功能以避免进一步触发。