如何在函数组件中保存变量的值

我有变量myinterval里面functional component有钩子,和我更新和ASIGN新价值这myinterval,只是里面useEffect。


但是在状态获取更新后myinterval保存了 prev 值,我的意思是我在功能组件中初始化的值。


function App(props) {


  const [name, setName] = useState('Muhammad');


  let myinterval = null;


  useEffect(()=>{


    myinterval = setInterval(()=> {}, 100);


  }, []);


  const print = async () => {

    setName('new name');

     console.log(myinterval);

  };


  return <button className="App" onClick={print}>hey</button>;

}

现在你可以看到,当我点击print function 时,第一次它不是空的,但第二次它是空的。


这是因为setName('new name');,实际上在setName('new name');调用之后,然后myinterval返回空值。


我想要的是?


我希望myinterval变量应该始终返回在内部重新初始化的值useEffect。


根据我的需要,我不能myinterval在function App(props){}.



交互式爱情
浏览 261回答 2
2回答

暮色呼如

这将仅在第一次渲染时设置间隔并在卸载时取消它useEffect(()=>{&nbsp; &nbsp; myInterval = setInterval(()=> {}, 100);&nbsp; &nbsp; return () => clearInterval(myInterval)&nbsp; }, []);}如果要存储对间隔 id 的引用,则不应使用普通变量(在每次渲染时设置),而应使用带有 useRef 钩子的 React reffunction App(props) {&nbsp; const [name, setName] = useState('Muhammad');&nbsp; const myInterval = useRef(null)&nbsp; useEffect(()=>{&nbsp; &nbsp; myInterval.current = setInterval(()=> {}, 100);&nbsp; &nbsp; return () => {&nbsp; &nbsp; &nbsp; if (myInterval.current) {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; clearInterval(myInterval.current)&nbsp; &nbsp; &nbsp; &nbsp; myInterval.current = null&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; }, []);&nbsp; const print = async () => {&nbsp; &nbsp; setName('new name');&nbsp; &nbsp; &nbsp;console.log(myInterval.current);&nbsp; };&nbsp; return <button className="App" onClick={print}>hey</button>;}

缥缈止盈

let myinterval = null;每次都运行,每次渲染useEffect(()=>{&nbsp; &nbsp; myinterval = setInterval(()=> {}, 100);}, []);只在 mount 上运行,留下myinterval一个null值修复您想要实现的目标:import React, { useState, useEffect, useMemo } from "react";import ReactDOM from "react-dom";import "./styles.css";function App() {&nbsp; const [name, setName] = useState("Muhammad");&nbsp; const [timeout, setTimeout] = useState("init value");&nbsp; useEffect(() => {&nbsp; &nbsp; setInterval(() => setTimeout("new value"), 3000);&nbsp; }, []);&nbsp; const print = async () => {&nbsp; &nbsp; setName("setting name");&nbsp; &nbsp; console.log(timeout);&nbsp; };&nbsp; return (&nbsp; &nbsp; <button className="App" onClick={print}>&nbsp; &nbsp; &nbsp; hey&nbsp; &nbsp; </button>&nbsp; );}const rootElement = document.getElementById("root");ReactDOM.render(<App />, rootElement);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript