RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 1025271
Accepted
Demon __
Demon __
Asked:2020-09-17 19:42:52 +0000 UTC2020-09-17 19:42:52 +0000 UTC 2020-09-17 19:42:52 +0000 UTC

useEffect hook 警告 - 从 React Hook useEffect 内部对“变量名”变量的赋值将在每次渲染后丢失

  • 772

我想将旧的类组件转换为功能性组件,但是useEffect.

旧类组件:

 state = {
        seconds: this.props.seconds,
        minutes: this.props.minutes,
 }
 componentDidMount() {
        /* IF GAME IS NOT PLAYED ONCE AND ROUTE IS NOT CHANGED THEN START TIMER */
        if(this.props.gameComplete === false && this.props.gameOver === false){ 
            this.startTimer();
        }
 }
 startTimer() {
        this.timer = setInterval(this.tick.bind(this), 1000)
 }
 componentWillUnmount() {
        clearInterval(this.timer);
 }

此代码完美运行(我无法显示整个组件,因为它太大了)。

我写了一个这样的功能版本:

let [seconds, setSeconds] = useState(props.seconds);
let [minutes, setMinutes] = useState(props.minutes);
let [timer,setTimer] = useState(null);

    useEffect(() => {
        /* IF GAME IS NOT PLAYED ONCE AND ROUTE IS NOT CHANGED THEN START TIMER */
        if(props.gameComplete === false && props.gameOver === false){ 
            const  startTimer = () => {
                setTimer(timer = setInterval(tick, 1000));
            }
            startTimer(); 
        }
        return () => {
            clearInterval(timer);
        }
    }, []);

此代码产生以下警告

'timer'从 React Hook useEffect 内部对变量的赋值将在每次渲染后丢失。要随着时间的推移保留该值,请将其存储在 useRef Hook 中并将可变值保留在“.current”属性中。否则,您可以直接在 useEffect react-hooks/exhaustive-deps 中移动此变量

是的,我用英语理解,每次渲染后,钩子内的分配都会丢失,嗯,然后如果我想使用componentDidMount上面在此代码的类版本中编写的生命周期替代方案,那么在哪里分配。

看不懂的第二个版本

如果你这样写:

    useEffect(() => {
        /* IF GAME IS NOT PLAYED ONCE AND ROUTE IS NOT CHANGED THEN START TIMER */
        if(props.gameComplete === false && props.gameOver === false){ 
            startTimer(); 
        }
        return () => {
            clearInterval(timer);
        }
    }, []);


    const  startTimer = () => {
        setTimer(timer = setInterval(tick, 1000));
    }

它产生以下错误:

React Hook useEffect 缺少依赖项:“props.gameComplete”、“props.gameOver”、“startTimer”和“timer”。要么包含它们,要么删除依赖数组 react-hooks/exhaustive-deps

我不想将useEffect来自 props 的变量和数据写在一个空数组中,它们应该只工作一次。

我该如何解决这个问题?我做错了什么?

UPD。

类中的tick函数

tick() {
    if(this.props.start === true){
        let {seconds,minutes} = this.state;
        this.setState({seconds:(seconds + 1)});
        if(seconds === 60){
            this.setState({seconds:(seconds = 0)});
            this.setState({minutes:(minutes + 1)});
            if(minutes === 60){
            this.setState({minutes:(minutes = 0)});
            }
        } 
    }
}

新功能tick

const tick = () => {
        if(props.start === true){
            setSeconds(seconds + 1);

            if(seconds === 60){
                setSeconds(seconds = 0);
                setMinutes(minutes + 1);
                if(minutes === 60){
                    setMinutes(minutes = 0);
                }
            } 
        }
    }
reactjs
  • 2 2 个回答
  • 10 Views

2 个回答

  • Voted
  1. Best Answer
    Mike
    2020-09-18T14:48:38Z2020-09-18T14:48:38Z

    见这里https://repl.it/@MikePodgorniy/hookTest

    import React, { Component, useRef, useCallback, useEffect, useState } from 'react';
    
    const TestComp = props => {
      const [seconds, setSeconds] = useState(0);
      const [minutes, setMinutes] = useState(0);
      const propsRef = useRef(props);
      useEffect(() => {
        propsRef.current = props;
      });
    
      // Апдейтим время с помощью callbackFunc
      const tick = useCallback(() => {
        if (propsRef.current.start === true) {
          setSeconds(s => {
            if (s >= 59) {
              setMinutes(m => (m === 60 ? 0 : m + 1));
              return 0;
            }
            return s + 1;
          });
        }
      }, [setSeconds, setMinutes, propsRef]);
    
      // ref создан один раз, можно не боятся добавляться его в зависимость к хукам
      const timerRef = useRef();
      // создаем и стопаем таймер в любом месте
      const startTimer = useCallback(() => {
        timerRef.current = setInterval(tick, 1000);
      }, [timerRef, tick]);
      const clearTimer = useCallback(() => clearInterval(timerRef.current), [timerRef]);
    
      useEffect(() => {
        if (propsRef.current.gameComplete === false && propsRef.current.gameOver === false) {
          startTimer();
        }
        return () => clearTimer();
      }, [propsRef, startTimer, clearTimer]);
      return (
        <div>{`${minutes}:${seconds}`}</div>
      );
    };
    
    class App extends Component {
      render() {
        return (
          <div className="App">
            <TestComp start gameComplete={false} gameOver={false} />
          </div>
        );
      }
    }
    
    export default App;

    • 2
  2. Mike
    2020-09-17T22:10:31Z2020-09-17T22:10:31Z

    如果是这样呢?可以有很多解决方案,只有几个。问题是tick必须作为依赖添加或在useEffect中声明,而不是在useEffect中使用赋值和外部函数。

    常见问题解答中有详细说明,还有很多要强调的内容: https ://reactjs.org/docs/hooks-faq.html#what-c​​an-i-do-if-my-effect-dependencies-change-too-often

    //v1
    const propsRef = useRef(props);
    const tick = useCallback(() => {...}, []);
    useEffect(() => {
      let timer;
      if(
        propsRef.current.gameComplete === false && 
        propsRef.current.gameOver === false
      ) { 
        timer = setInterval(tick, ...);
      }
      return () => clearInterval(timer);
    }, [tick]);
    
    
    //v2
    const propsRef = useRef(props);
    
    useEffect(() => propsRef.current = props);
    
    useEffect(() => {
      const tick = () => {
        propsRef.current ... //ваша логика
      }
      let timer;
      if(
        propsRef.current.gameComplete === false && 
        propsRef.current.gameOver === false
      ) { 
        timer = setInterval(tick, ...);
      }
      return () => clearInterval(timer);
    }, []);

    • 1

相关问题

  • 做出反应。旋转木马

  • 如何在 react-dates 日历中定义月份切换?

  • SSR 和 CSR 有什么区别?

  • Redux-Saga - 观察者,takeEvery

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    根据浏览器窗口的大小调整背景图案的大小

    • 2 个回答
  • Marko Smith

    理解for循环的执行逻辑

    • 1 个回答
  • Marko Smith

    复制动态数组时出错(C++)

    • 1 个回答
  • Marko Smith

    Or and If,elif,else 构造[重复]

    • 1 个回答
  • Marko Smith

    如何构建支持 x64 的 APK

    • 1 个回答
  • Marko Smith

    如何使按钮的输入宽度?

    • 2 个回答
  • Marko Smith

    如何显示对象变量的名称?

    • 3 个回答
  • Marko Smith

    如何循环一个函数?

    • 1 个回答
  • Marko Smith

    LOWORD 宏有什么作用?

    • 2 个回答
  • Marko Smith

    从字符串的开头删除直到并包括一个字符

    • 2 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5