首页 > 解决方案 > 在 react-router 中使用 useRef 时,useRef.current 总是返回 undefined

问题描述

我正在尝试通过使用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"

标签: reactjsreact-routerreact-hooksreact-router-dom

解决方案


您不能使用单击链接。

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

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

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

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


推荐阅读