当我运行它时,它呈现的方式不同,尽管它与我的初学者POV相同. 例如,我不能在控制台开发工具中展开第一个div,但我可以展开第二个div!

Link, I haven't the right to post images

为什么?

import React from "react"

export default function App() {

    const [time, setTime] = React.useState(0)

    React.useEffect(() => {
        const lol = setTimeout(() => setTime(prev => prev + 1), 100)
        return () => clearTimeout(lol)
    }
        , [time]
    )

    function ComponentTimer() {
        return <div> (I can't open this div in the console) Time : {time / 10} sec</div>
    }

    return (
        <main>
            {<ComponentTimer />}
            <div> (but I can open this one) Time : {time / 10} sec</div>
        </main>
    )
}

推荐答案

在第一个示例中,它是一个组件,您在100ms之后更改状态,这将重新呈现整个组件.如果您想看到两者完全相同,您所要做的就是从外部提取ComponentTimer,并将time作为props 传递为:

STACKBLITZ DEMO

function ComponentTimer({ time }) {
  return (
    <div> (I can't open this div in the console) Time : {time / 10} sec</div>
  );
}
export default function App() {
  const [time, setTime] = React.useState(0);

  React.useEffect(() => {
    const lol = setTimeout(() => setTime((prev) => prev + 1), 100);
    return () => clearTimeout(lol);
  }, [time]);

  return (
    <main>
      <ComponentTimer time={time} />
      <div> (but I can open this one) Time : {time / 10} sec</div>
    </main>
  );
}

Reactjs相关问答推荐

如何在useEffect中使用useParams()

两条react 路由的行为不同.有没有人能解释一下,我已经找了好几天了

Redux工具包-useSelector如何通过Reducer引用InitialState?

在每页上应用字体-NextJS

我如何在不被 destruct 的情况下将导航栏固定在顶部?

为什么我得不到我想要的数据?

React 错误无法读取未定义的属性(读取id)#react

使用 MUI 菜单时添加新 html 元素时布局意外滚动跳转

Chart.js如何go 除边框

在 React 中使用forwardRef时无法声明自定义属性

Next.js `getLayout` 函数没有被调用

为什么 useEffect 的初始化对于加载 localStorage 不起作用?

在添加了useplacesautocomplete后,在构建React/Next.js项目时,NPM抛出类型期望的错误

在 Nextjs13 应用程序目录中呈现从 supabase 获取的数据

臭名昭著的测试未包含在 act(...) 中

有没有办法根据 Rechart 中的 activeDot 更改值?

setState 改变对象引用

react 页面更新

如何在 v6.4 中将 Auth0 提供程序与新的 createBrowsereRouter 一起使用?

ReactJS:按钮启用禁用更改 colored颜色