相关疑难解决方法(0)

每 3 秒更改一次文本 React useEffect

我尝试使用 useEffect() 和 setInterval() 每 3 秒更改一次文本。现在它只更改文本一次,然后就不再更改了。我究竟做错了什么?

编辑:我正在使用库“react-spring”

  const [toggle, setToggle] = useState(false)

  useEffect(() => {
    setInterval(() => {
      switch (toggle) {
        case false: setToggle(true)
        break;
        case true: setToggle(false)
        break;
      }
    }, 3000);
  }, [])

{transitions.map(({ item, props }) => item
  ? <animated.div style={props}>Text that changes #1</animated.div>
  : <animated.div style={props}>Text that changes #2</animated.div>)}
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-hooks use-effect

3
推荐指数
1
解决办法
7364
查看次数

为什么需要useRef在组件函数之外包含可变变量而不定义变量?

我已阅读了《使用效果的完全指南-过度反应应对潮流》

该示例表明,如果我们想获取最新的count,我们可以useRef用来保存可变变量,并在异步函数laster中获取它:

function Example() {
  const [count, setCount] = useState(0);
  const latestCount = useRef(count);

  useEffect(() => {
    // Set the mutable latest value
    latestCount.current = count;
    setTimeout(() => {
      // Read the mutable latest value
      console.log(`You clicked ${latestCount.current} times`);
    }, 3000);
  });
  // ...
}
Run Code Online (Sandbox Code Playgroud)

但是,我可以通过在组件函数外部创建一个变量来执行相同的操作,例如:

import React, { useState, useEffect, useRef } from 'react';

// defined a variable outside function component
let countCache = 0;

function Counter() {
  const [count, setCount] = useState(0); …
Run Code Online (Sandbox Code Playgroud)

reactjs react-hooks

2
推荐指数
2
解决办法
139
查看次数

标签 统计

react-hooks ×2

reactjs ×2

javascript ×1

use-effect ×1