如何使用反应路由器 useParams() 或 window.localStorage()

How to use either react router useParams() or window.localStorage()

在我的场景中,组件应该从 URL 或 localStorage 中获取值,但是当我尝试从 useParams() 获取值时,它会抛出此错误:

Uncaught ReferenceError: useParams is not defined

我的代码是:

const { userId } = useParams() || props;

我想你没有导入 useParams,在这种情况下,请在你的文件顶部导入:

import {useParams} from "react-router-dom"

然后做:

let {userId} = useParmas();
if(!userId) userId = props.userId;

因为 useParams return 一个对象,一个空对象,像这样 {} 如果没有任何参数,但 {} 不是假的,所以通过做所以 useParams() || props,如果你的 url 中没有 userId 参数,你将始终未定义。

确保您已导入 useParams。如果您已经导入了它,请尝试执行此操作。

let { userId } = useParams();
if(!userId) userId = props.userId;

如果您使用的是 class 组件,则必须改用 withRouter()

import { withRouter } from "react-router";


class Whatever extends Component {
  render() {
    const { userId } = this.props.match.params;
    return null;
  }
}