【问题标题】:useRef.current always returns undefined when useRef is used in react-router <Link>在 react-router <Link> 中使用 useRef 时,useRef.current 总是返回 undefined
【发布时间】:2020-10-22 01:24:08
【问题描述】:

我正在尝试使用 useRef 钩子创建一个 ref 并将这个 ref 添加到 react-router Link。然后在 useEffect 钩子中,我试图访问我的 ref 的 current 属性,但它始终是 undefined。我在自定义组件或常见 html 元素的多个场合中以相同的方式使用 useRef 并且它始终有效。关于它为什么不适用于 Link 的任何想法?

import React, { useEffect, useRef } from 'react';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';

const MyComponent = ({ code, getCode }) => {
  const linkRef = useRef();

  useEffect(() => {
    const { current } = linkRef || {};
    if (linkRef !== undefined && current) {
      console.log(current); // current is always undefined and it shouldn't
      console.log(code);
    }
  }, [code, linkRef]);

  return (
    <div>
      <Link
        ref={linkRef}
        to={{
          pathname: '/enter-code',
          query: { code },
        }}
      >
        {'Link'}
      </Link>
      <button onClick={() => getCode()} type="button">
        {'Get Code'}
      </button>
    </div>
  );
};

MyComponent.propTypes = {
  code: PropTypes.string,
  getCode: PropTypes.func,
};

export default MyComponent;

我正在使用:

"react": "^16.12.0"
"react-router-dom": "^5.1.2"

【问题讨论】:

  • 你使用什么版本的reactreact-router
  • @HagaiHarari 我刚刚编辑了问题,添加了版本。
  • 可能和这个有关? stackoverflow.com/q/56541342/806975
  • @GuillermoGutiérrez 我也尝试将 ref 作为依赖项传递给 useEffect,但它仍然不起作用。

标签: reactjs react-router react-hooks react-router-dom


【解决方案1】:

你不能使用点击链接。

正如打字稿错误所说,链接组件不能作为简单的锚标记单击。对此有两种建议的解决方案。

  1. 将链接更改为并在 useRef 中使用 HTMLAnchorElement 类型。

  2. 或者如果你想继续使用 react-router-dom 中的 Link 组件,你可以访问 link 组件的 props。您可以访问链接的“to”,但请确保仅在“to”道具中指定了直接 URL。

    if (linkRef !== undefined &amp;&amp; current) {window.location.assign(linkRef.current.props.to.toString()); // redirect to the to prop on Link component }

【讨论】:

  • 这可能回答了我将要面对的下一个问题并提前感谢,但这里的实际问题是为什么“当前”总是未定义。我什至在尝试单击按钮之前就遇到了这个问题。 linkRef.current 始终未定义
  • 如果适合你可以考虑用锚标签替换
  • // 尝试使用 innerRef 代替 ref
  • 我想在“/enter-code”打开一个新标签,并将代码作为属性传递给新页面。这就是我使用 react-router 而不仅仅是锚标记的原因。
  • 我也尝试过 innerRef。相同的行为,经过 React 16 之后的一些研究,不需要 innerRef,ref 也被处理。
猜你喜欢
  • 2020-11-19
  • 1970-01-01
  • 2021-03-29
  • 1970-01-01
  • 1970-01-01
  • 2022-01-26
  • 2017-03-18
  • 2016-01-16
  • 1970-01-01
相关资源
最近更新 更多