为什么setInterval中更新的用户名不反映在视图中

问题描述 投票:0回答:3

为什么不只更新更新但不更新用户名

import React, { useState } from "react";
import ReactDOM from "react-dom";

function ReposGrid({ id }) {
  const [count, setCount] = useState(0);
  var username = "Deen";
  let timeId = setInterval(() => {
    setCount(count + 1);
    username = username + count;
    console.log("shows updated username ", username);
  }, 1000);

  React.useEffect(() => {
    document.title = `Hello, ${username} ${count}`; //this updates title everytime but username is still old
  }, [count]);

  console.log("shows old instead of updated username ", username); //doesn't work.doesn't show updated username value

  return <h1>{username}</h1>;
}

const rootElement = document.getElementById("root");
ReactDOM.render(<ReposGrid />, rootElement);
javascript reactjs react-hooks settimeout
3个回答
0
投票

之所以失败,是因为React不知道名称变量,因为如上所述,它不是状态的一部分。因此,使用setState时看不到任何更新。


0
投票

代码遵循正确的行为,让我解释一下:

  1. setInterval被执行并在事件队列中排队。
  2. 此时注意,其中的代码未执行,但推迟到1秒才能执行。
  3. 接下来您进入useEffect功能。请注意,setInterval内部的代码仍未执行。
  4. 您在此处使用username的先前/原始值更新标题。
  5. 接下来,console.log将用户名的先前值返回到header标记内。

[[此时,事件队列中的代码被放回堆栈并执行(即,至少1秒钟后)。

    setCount(count + 1)被调用。由于状态变量已更新,因此useEffect也将被执行,函数的其余部分(包括标题的更新)也将被执行]
  1. 现在下一条语句将被执行username = username + count。由于这不是状态变量,所以即使变量更新,也不会调用useEffect也不更新document.title
  2. 现在用户名已更新(但没有副作用)。
  3. 下一个console.log("shows updated username ", username)
  4. 这应该是console.log的更新值。

0
投票
需要一点点清理。

import React, { useState } from "react"; import ReactDOM from "react-dom"; function ReposGrid({ id }) { const [count, setCount] = useState(0); let username = "Dean " ; React.useEffect(() => { let timeId = setInterval(() => { setCount(count + 1); }, 1000); return () => { clearInterval(timeId); }; }, [count]); React.useLayoutEffect(() => { document.title = `Hello, ${username} ${count}`; }, [username, count]); console.log("shows old instead of updated username ", username, count); //doesn't work.doesn't show updated username value return ( <h1> {username} {count} </h1> ); } const rootElement = document.getElementById("root"); ReactDOM.render(<ReposGrid />, rootElement);

 

"use strict"; function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(n); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function ReposGrid(_ref) { var _ref$username = _ref.username, username = _ref$username === void 0 ? "User" : _ref$username; var _useState = React.useState(0), _useState2 = _slicedToArray(_useState, 2), count = _useState2[0], setCount = _useState2[1]; React.useEffect(function () { var timeId = setInterval(function () { setCount(count + 1); }, 1000); return function () { clearInterval(timeId); }; }, [count]); React.useLayoutEffect(function () { document.title = "Hello, ".concat(username, " ").concat(count); }, [username, count]); console.log("shows old instead of updated username ", username, count); //doesn't work.doesn't show updated username value return /*#__PURE__*/React.createElement("h1", null, username, count); } var rootElement = document.getElementById("root"); ReactDOM.render( /*#__PURE__*/React.createElement(ReposGrid, null), rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.10.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.10.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>
© www.soinside.com 2019 - 2024. All rights reserved.