如何使用 React-router-dom 版本 6 useNavigate 和 typescript 传递参数

Gri*_*420 17 javascript reactjs

我正在尝试使用react-router-dom版本6中的useNavigate将变量发送id到另一个页面。这是我正在尝试的:

const handleSelect = (id: number) => {
    navigate('/Players', {
      userId: id,
    });
  };
Run Code Online (Sandbox Code Playgroud)

但是我收到错误:Argument of type '{ userId: number; }' is not assignable to parameter of type 'NavigateOptions'. Object literal may only specify known properties, and 'userId' does not exist in type 'NavigateOptions'.ts(2345)

我找不到有关 NavigateOptions 或它正在寻找的类型的任何有用信息。如果我删除该参数,那么我可以很好地userId导航到该页面。Player这只是导致问题的参数。对于这个问题我能做什么?有人可以提供一些这方面的文档吗?

NavigateOptions 类型的参数示例是什么?

小智 31

您的意思是向导航添加状态吗?原来的:

const handleSelect = (id: number) => {
    navigate('/Players', {
      userId: id,
    });
  };
Run Code Online (Sandbox Code Playgroud)

更改为(带状态):

const handleSelect = (id: number) => {
    navigate('/Players', {
      state: {
        userId: id,
      }
    });
  };
Run Code Online (Sandbox Code Playgroud)

然后就可以props.location.state.userIdPlayers页面中引用了。

// Players Page

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

const location = useLocation();

// get userId
let userId = location.state.userId;
Run Code Online (Sandbox Code Playgroud)

  • 这不适用于打字稿。上面的问题是关于打字稿的明确问题 (3认同)
  • 它在 Typescript 上抛出错误。“类型‘{}’上不存在属性‘props’。ts(2339)” (2认同)