useRef.current 总是返回 undefined,当 useRef 用于 react-router <Link>时



我正在尝试使用useRef钩子创建一个引用并将此引用添加到反应路由器链接中。然后在useEffect钩子中,我正在尝试访问我的 ref 的当前属性,但它始终是未定义的。我已经在多个场合以相同的方式使用自定义组件或常见的 html 元素,并且它总是有效。关于为什么它不适用于链接的任何想法?

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"

你不能使用点击链接。

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

  1. 在 useRef 中更改链接并使用 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 }

相关内容

最新更新