如何在功能组件内部保存变量的值

时间:2019-10-12 08:14:11

标签: javascript reactjs react-native react-hooks

我在class Abc(object): def __init__(self,words): self.words = words def convert_int(self, s): #updated try: return int(s) except ValueError: return s def test(self): words = self.words words = self.convert_int(words) #updated return words f = Abc("12345") print(f.test()) 内有带有 Hooks 的变量myinterval,并且我在此functional component的内部更新并赋了新值 myinterval

但是状态更新后,useEffect保留了prev值,我的意思是我在功能组件内部初始化了该值。

myinterval

现在,当我单击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>; } 功能时,您会看到,第一次它不是null,但是第二次它是null。

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

我想要什么?

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

根据我的需要,我无法在useEffect之外声明我的myinterval变量。

这是一个示例,我向它展示了非常简单的内容。 Simple Code Example

2 个答案:

答案 0 :(得分:1)

let myinterval = null;

每次在每个渲染器上运行

useEffect(()=>{
    myinterval = setInterval(()=> {}, 100);
}, []);

仅在安装时运行,而使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);

答案 1 :(得分:1)

这将仅在第一次渲染时设置间隔,并在卸载时取消间隔

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>;
}