简体   繁体   English

在初始渲染时为 refs 反应(挂钩)不同的值

[英]React (hooks) different value for refs on initial render

Can someone explain to me what is the reason for this situation!有人可以向我解释这种情况的原因是什么!

Let's say I have a function which generates a random value on initial render.假设我有一个在初始渲染时生成随机值的函数。 Then I assign the result using ref to keep the value unchanged after subsequent component updates.然后我使用 ref 分配结果以在后续组件更新后保持值不变。 After that I assign the ref value to some state.之后,我将 ref 值分配给某个状态。 The state is initialized with the ref value inside setTimeout.状态用 setTimeout 中的 ref 值初始化。

import React, { useRef, useState } from "react";
import value from "./example";

function App(){

  const v = useRef(word());

  console.log(v.current); // Here for example the value is "test"

  setTimeout(() => {
    console.log(v.current); // Here the value is different
  }, 1000)

  const [state, setState] = useState(v.current);

  return (
    <div>{v.current}</div>
  )
}

I use setTimeout to illustrate the case but even without it the result is the same the state will be crated with different word although there is no component update.我使用 setTimeout 来说明这种情况,但即使没有它,结果也是相同的,尽管没有组件更新,但状态将用不同的词创建。

How many times the component is render for the first initialization although there is no state change?尽管没有状态变化,组件在第一次初始化时渲染了多少次?

You are running your app in strict mode.您正在以严格模式运行您的应用程序。 Go to index.js and comment out the strict mode tag.转到 index.js 并注释掉严格模式标签。 You will find a single render.你会发现一个渲染。

This only applies to development mode.这仅适用于开发模式。 Lifecycles will not be double-invoked in production mode.生命周期不会在生产模式下被双重调用。

This is done by intentionally double-invoking the following functions:这是通过有意重复调用以下函数来完成的:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM