首页 > 解决方案 > React TypeScript:react-router-dom 中 useLocation() 的正确类型

问题描述

我正在努力为这种情况找到合适的类型。这是登录后重定向的简化版本。以下会产生编译器错误:

Property 'from' does not exist on type '{} | { from: { pathname: string; }; }'.

添加as any到使用location.state修复编译器错误但它很丑陋并且 linter 抱怨。

import React from "react";
import { useLocation } from "react-router-dom";

const AuthLayer: React.FC = (props) => {
  const location = useLocation();

  const { from } = location.state || { from: { pathname: "/" } };

  return <p></p>;
};

export default AuthLayer;

标签: reactjstypescripttypescript-typingsreact-router-dom

解决方案


您可以创建特定类型或接口来描述您的位置状态,然后在调用useLocation挂钩时使用它:

import React from "react";
import { useLocation } from "react-router-dom";

interface LocationState {
  from: {
    pathname: string;
  };
}

const AuthLayer: React.FC = (props) => {
  const location = useLocation<LocationState>();

  const { from } = location.state || { from: { pathname: "/" } };

  return <p></p>;
};

export default AuthLayer;

推荐阅读