React TypeScript:react-router-dom 中 useLocation() 的正确类型

Jim*_*eer 10 typescript reactjs typescript-typings react-router-dom

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

Property 'from' does not exist on type '{} | { from: { pathname: string; }; }'.
Run Code Online (Sandbox Code Playgroud)

添加修复编译器错误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;
Run Code Online (Sandbox Code Playgroud)

小智 24

类型断言在这里可以工作。

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

type LocationState = {
  from: {
    path: string;
  }
}

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

  const { from } = location.state as LocationState;

  return <p></p>;
};

export default AuthLayer;
Run Code Online (Sandbox Code Playgroud)

另外,请记住根据您的要求定义类型。例如,您可能正在使用navigate(state.from).

为此,将类型定义为 -

type LocationState = {
  from : string;
}
Run Code Online (Sandbox Code Playgroud)


fal*_*sky 17

你可以创建一个特定的类型或接口来描述你的位置状态,然后在调用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;
Run Code Online (Sandbox Code Playgroud)

  • @duduwe 在版本 6 中有点不同, const locationState = useLocation().state as {id: string}; const id = 位置状态.id; (2认同)

omd*_*jin 7

您可以使用“历史”中的位置。

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


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

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

  return <p></p>;
};

export default AuthLayer;
Run Code Online (Sandbox Code Playgroud)

  • 我的说“预期有 0​​ 个类型参数,但得到了 1。” (5认同)