reactjs - 在效果中 setState 之后 React 功能组件渲染两次

标签 reactjs react-hooks react-functional-component

我写了简单的代码如下

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

export default function App() {
  const [count, setCount] = useState(1);

  useEffect(() => {
    setCount(2);
  }, [count]);

  console.info("render: ", count);
  return <div>{count}</div>;
}

控制台输出为

render:  1
render:  2
render:  2

为什么“render:2”输出两次

最佳答案

问题在于您无条件更新用作依赖项的状态。

此行为并不意外。

参见Bailing out of a state update

If you update a State Hook to the same value as the current state, React will bail out without rendering the children or firing effects. (React uses the Object.is comparison algorithm.)

Note that React may still need to render that specific component again before bailing out. That shouldn’t be a concern because React won’t unnecessarily go “deeper” into the tree. If you’re doing expensive calculations while rendering, you can optimize them with useMemo.

在初始渲染(即第一个日志)时,count 为 1。 useEffect Hook 运行并将状态更新排入队列,然后处理更新。

下一次渲染(第二个日志)时,计数 为 2。 count 状态值已更新,因此 useEffect Hook 回调运行并将另一个状态更新排入同一值,然后处理该更新。

在下一次渲染(即第三个日志)时,count 仍为 2。 count 状态尚未更改,因此不会触发 useEffect Hook 回调。

关于reactjs - 在效果中 setState 之后 React 功能组件渲染两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71554217/

相关文章:

reactjs - react |将数据从父组件传递给子组件

javascript - 类型 'State' 的参数不可分配给类型 'never' 的参数

reactjs - 单击按钮时,不会添加数据

reactjs - react : Fix missing dependency warning useEffect with Refs

reactjs - 功能组件中的 Refs 数组以通过 classList 更改单个项目的类名

javascript - React 函数式组件 - 说它不是一个函数

javascript - react : AutoFocus on Input field inside Modal

javascript - 如何计算现在日期和恒定日期之间的差异。并像 1d,1m,1w 一样编辑它

javascript - 如何将 scss 文件与 create-react-app 一起使用?

javascript - React 函数组件状态 - 重新渲染太多。 React 限制渲染次数以防止无限循环