2 回答
TA贡献1853条经验 获得超9个赞
这将仅在第一次渲染时设置间隔并在卸载时取消它
useEffect(()=>{
myInterval = setInterval(()=> {}, 100);
return () => clearInterval(myInterval)
}, []);
}
如果要存储对间隔 id 的引用,则不应使用普通变量(在每次渲染时设置),而应使用带有 useRef 钩子的 React ref
function App(props) {
const [name, setName] = useState('Muhammad');
const myInterval = useRef(null)
useEffect(()=>{
myInterval.current = setInterval(()=> {}, 100);
return () => {
if (myInterval.current) {
clearInterval(myInterval.current)
myInterval.current = null
}
}
}, []);
const print = async () => {
setName('new name');
console.log(myInterval.current);
};
return <button className="App" onClick={print}>hey</button>;
}
TA贡献2041条经验 获得超4个赞
let myinterval = null;
每次都运行,每次渲染
useEffect(()=>{
myinterval = setInterval(()=> {}, 100);
}, []);
只在 mount 上运行,留下myinterval一个null值
修复您想要实现的目标:
import React, { useState, useEffect, useMemo } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
const [name, setName] = useState("Muhammad");
const [timeout, setTimeout] = useState("init value");
useEffect(() => {
setInterval(() => setTimeout("new value"), 3000);
}, []);
const print = async () => {
setName("setting name");
console.log(timeout);
};
return (
<button className="App" onClick={print}>
hey
</button>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
添加回答
举报