【发布时间】: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"
【问题讨论】:
-
你使用什么版本的
react和react-router? -
@HagaiHarari 我刚刚编辑了问题,添加了版本。
-
可能和这个有关? stackoverflow.com/q/56541342/806975
-
@GuillermoGutiérrez 我也尝试将 ref 作为依赖项传递给 useEffect,但它仍然不起作用。
标签: reactjs react-router react-hooks react-router-dom