为什么 ref 在条件渲染中没有获取值

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

我有一个有条件渲染的组件,我通过React的forwardRef将引用传递给它,但是当条件满足并且组件渲染时,引用仍然没有任何值, 我该怎么办?

这是我的模拟代码

import { useEffect, useState, useRef } from "react";
import "./styles.css";
import Table from "./Table";

export default function App() {
  const [list, setList] = useState([]);
  const ref = useRef(null);
  useEffect(() => {
    setTimeout(() => {
      setList(["faraz"]);
    }, 1000);
  }, []);
  console.log("ref************", ref);
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      {!!list.length && <Table ref={ref} />}
    </div>
  );
}

还有我的孩子和条件渲染组件

import React from "react";

const Table = React.forwardRef((props, ref) => {
  return (
    <div>
      <p>test</p>
      <div ref={ref}></div>
    </div>
  );
});
export default Table;

我尝试将 ref 和前向 ref 传递给子组件,但 ref 从未获取值,如何在条件渲染组件上设置 ref 值

reactjs react-hooks ref react-forwardref
1个回答
0
投票

在您的示例中

ref
实际上确实有一个值,只是没有被记录。

要了解原因,让我们逐步分析您提供的代码中发生的情况:

  1. 状态初始化:
    list = []; ref.current = null
  2. console.log("ref************", ref); // logs: '{current: null}'
  3. 应用程序渲染
  4. 因为
    list.length === 0
    ,Table 不会渲染,所以
    ref.current
    保持为 null
  5. useEffect
    运行,触发状态更新
  6. 新状态:
    list = ["faraz"]; ref.current = null
  7. console.log("ref************", ref); // logs: '{current: null}'
  8. 应用程序重新渲染
  9. 因为
    list.length === 1
    ,表格也会渲染并设置
    ref.current = {current: HTMLDivElement {...}}
  10. 由于参考更新不会触发新的渲染并且没有新的状态更新,因此应用程序不会重新渲染,并且您的
    console.log
    没有机会记录新的
    ref.current
    值。

要验证您的

ref.current
值是否实际设置,您可以更新代码以渲染 Table,无论
list
长度如何,这都会在
first
渲染上设置 ref.current,从而导致在第二次渲染期间出现
console.log
记录其值。

您可以在此处找到具有描述的更新的代码https://playcode.io/1863189

© www.soinside.com 2019 - 2024. All rights reserved.