【问题标题】:Preact setState hook wont work within a setIntervalPreact setState hook 在 setInterval 中不起作用
【发布时间】:2019-04-26 02:48:41
【问题描述】:

CodeSandbox
尝试在 setIntervalpreact/hook 中使用 useState。这不起作用,看起来永远迭代它正在执行以前的调用堆栈(?)。有人可以帮助我理解并帮助我解决这个问题吗?

import {h} from 'preact';
import {useState} from 'preact/hooks'
const interests = [
  {name: 'the future',},
  {name: 'architecture',},
  {name: 'my work',},
  {name: 'your work',},
  {name: 'collaboration',},
  {name: 'dank memes',},
  {name: 'OOP vs. Functional',},
  {name: 'design',},
  {name: 'guitar',},
  {name: 'inspirational people',},
  {name: 'love',},
  {name: 'travel',},
  {name: 'singularity',},
  {name: 'creativity',},
  {name: 'mixed, virtual, augmented reality',},
  {name: 'art',},
  {name: 'imagination',},
  {name: 'problem solving',},
  {name: 'space',},
  {name: 'cooking',},
  {name: 'FOMO',},
  {name: 'ontological design',},
  {name: 'flow state',},
  {name: 'foreign languages',},
  {name: 'streaming on the internet',},
  {name: 'video games',},
  {name: 'coffee',},
  {name: 'crypto currency',},
  {name: 'javascript fatigue',},
  {name: 'framework wars',},
  {name: 'blockchain',},
  {name: 'smart contracts',},
  {name: 'just emailing me'},
  {name: 'ethereum'},
  {name: 'university'},
  {name: 'engineering software'},
];


const RunningHeader = () => {
  const [count, setCount] = useState(0);
  setInterval(() => {setCount(c => c + 1)}, 1000);
  return (
    <header>
      <p>{interests[count].name}</p>
    </header>
)}

export {RunningHeader};

【问题讨论】:

    标签: asynchronous state setinterval react-hooks preact


    【解决方案1】:

    您需要使用 setTimeout。 setInterval 永远不会被取消,因此每次渲染都会添加一个新的 1s 重复计时器。这是您的沙盒以 2 种不同方式修复(setTimeout 或使用 useEffect 在挂载上安装重复计时器):

    https://codesandbox.io/s/vy0ww725j0

    【讨论】:

      【解决方案2】:

      useEffect 没有依赖关系 [] 将充当 componentDidMount 来挂载我们的间隔,我们可以返回一个函数来在卸载时调用,我们应该在卸载时清除我们的间隔以避免内存泄漏。

      useEffect(() => {
        const id = setInterval(() => {
          setCount(c => c + 1);
        }, 1000);
        return () => clearInterval(id);
      }, []);
      

      【讨论】:

      • 感谢您澄清return () =&gt; clearInterval(id)
      猜你喜欢
      • 2018-05-08
      • 2016-09-22
      • 1970-01-01
      • 1970-01-01
      • 2021-06-02
      • 2016-01-21
      • 2021-02-02
      • 1970-01-01
      • 2011-11-07
      相关资源
      最近更新 更多