ReactJS:为什么一种状态的值不同?

所以我正在使用非常基本的组件进入 Reactjs。我从不同的函数注销相同的状态,但我看到的是不同的值。


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


const Test = props => {

  const [count, setCount] = useState(0);


  useEffect(()=>{

      setInterval(() => {

        console.log("count in interval is:", count);

      }, 1000);

  },[props]);


  function btnClick() {

    const newCount = count + 1;

    setCount(newCount);

    console.log("count changed to: ", newCount);

  }

  return (

    <div>

      count is {count}

      <br></br>

      <button onClick={btnClick}>+</button>

    </div>

  );

};


export default Test;

单击并等待后输出,日志为:


Test.js:8 count in interval is: 0

Test.js:15 count changed to:  1

Test.js:15 count changed to:  2

Test.js:15 count changed to:  3

Test.js:15 count changed to:  4

(8 rows) Test.js:8 count in interval is: 0

我希望两个函数中的“计数”相同。任何人都可以解释这一点吗?


非常感谢。


大话西游666
浏览 239回答 2
2回答

慕娘9325324

Test只有一个setInterval函数,其中countalways 0。因为它仅在初始渲染期间创建。它从未有另一个setInterval创建因为效果从来没有得到触发与[props]作为依赖。要setInterval在每次重新渲染时更改 's 计数:移除依赖在效果中返回一个清理函数useEffect(&nbsp; () => {&nbsp; &nbsp; const t = setInterval(() => {&nbsp; &nbsp; &nbsp; console.log("count in interval is:", count);&nbsp; &nbsp; }, 1000);&nbsp; &nbsp; return () => clearInterval(t); // cleanup on every re-render&nbsp; }&nbsp; // no dependency: effect runs on every re-render);但是上面的代码会有一个警告:“缺少count依赖”因此,只需添加count为依赖项即可仅在count更改时运行效果。useEffect(&nbsp; () => {&nbsp; &nbsp; const t = setInterval(() => {&nbsp; &nbsp; &nbsp; console.log("count in interval is:", count);&nbsp; &nbsp; }, 1000);&nbsp; &nbsp; return () => clearInterval(t); // cleanup "old" setInterval&nbsp; }&nbsp; , [count] // ony run effect every time count changes);

皈依舞

的值count不会改变,这是预期的行为,虽然不是一个明显的行为。看,你甚至声明count为 a&nbsp;const count,它是不可变的。相反发生的事情是在第一次渲染期间count获得了0.&nbsp;的值count从不改变,而是在Test每次更改状态时调用组件,并且函数useState为常量分配不同的值count,每次都是新的常量。因此,在第一次渲染期间,被调用的函数内部const count的闭包捕获了setInterval的值,并且该值0永远保持不变。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript