使用 useContext 时停止重新渲染

时间:2021-05-01 07:22:05

标签: javascript reactjs

我正在使用 useContext 意外地重新渲染所有内容。您可以在附图中看到结果。我的 count 在一秒内更新多次

**//app component**

import React, { useState, useContext, memo } from "react";
import StateProvider from "./Components/StateComp";
import Count from "./Components/Count";
import CountUpdater from "./Components/CountUpdater";
const App = memo(() => {
  return (
    <>
      <StateProvider>
        <Count/>
        <CountUpdater />
      </StateProvider>
    </>
  );
})
export default App;


**//StateProvider comp**

import React, { useState, createContext } from "react";
export const StateContext = createContext();
function StateProvider({children}) {
  const [count, setCount] = useState(1000);
  return <StateContext.Provider value={{count, setCount}}>{children}</StateContext.Provider>;
}
export default StateProvider;


**//Count Comp**

import React, { useContext } from "react";
import { StateContext } from "./StateComp";
function CountComp() {
  const { count } = useContext(StateContext);
  return <h1>Count: {count}</h1>;
}
export default CountComp;


**//CountUpdater comp**

import React, { useContext, useEffect } from "react";
import { StateContext } from "./StateComp";
function CountUpdater() {
  const { count, setCount } = useContext(StateContext);
  setInterval(() => {
    setCount(count + 1);
    console.log("Updated count: ", count);
  }, 1000);
  return <h1>Updated count: {count}</h1>;
}
export default CountUpdater;

我该如何解决这个问题,备忘录不起作用,我尝试使用 useEffect 添加依赖项,但它太没用了?

控制台结果:

Console Results

2 个答案:

答案 0 :(得分:1)

您需要在 useEffect 中清除超时。

function CountUpdater() {
    const { count, setCount } = useContext(StateContext);
    useEffect(() => {
        let interval = setInterval(() => {
            setCount(count + 1);
            console.count('updated');
        }, 1000);

        return () => clearInterval(interval);
    }, [count, setCount]);

    return <h1>Updated count: {count}</h1>;
}

答案 1 :(得分:1)

在@keith 的帮助下,我找到了答案。就像他说的,我需要把 clearInterval 放在 return() 上,也放在 useEffect

**//CountUpdater comp**

function CountUpdater() {
  const { count, setCount} = useContext(StateContext);
  
  useEffect(() => {
    const interval= setInterval(() => {
      setCount(count+ 1);
      console.log("Updated Count: ", count);
    }, 1000);
    return () => clearInterval(interval);
  }, [count, setCount]);
  
  return <h1>Updated count: {count}</h1>;
}

export default CountUpdater;