javascript 如何使用React-router-dom版本6传递参数使用导航和类型脚本

nfeuvbwi  于 2023-06-28  发布在  Java
关注(0)|答案(3)|浏览(90)

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

const handleSelect = (id: number) => {
    navigate('/Players', {
      userId: id,
    });
  };

但是我得到了错误: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类型的参数示例是什么?

oaxa6hgo

oaxa6hgo1#

你的意思是在导航中添加状态吗?原件:

const handleSelect = (id: number) => {
    navigate('/Players', {
      userId: id,
    });
  };

变更为(带状态):

const handleSelect = (id: number) => {
    navigate('/Players', {
      state: {
        userId: id,
      }
    });
  };

然后您可以在Players页面中引用props.location.state.userId

// Players Page

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

const location = useLocation();

// get userId
let userId = location.state.userId;
bsxbgnwa

bsxbgnwa2#

在玩家页面中,“props.location.state.userId”将不再起作用。在播放器页面中执行以下操作:

import { useLocation } from "react-router-dom";
const location = useLocation();
location.state.userId
aamkag61

aamkag613#

将用户重定向到/Players页面时,需要在optionsstate属性中发送元数据:

const handleSelect = (id: number) => {
    navigate('/Players', {
      state: {
        userId: id,
      }
    });
  };

然后,您可以通过在Players页面中使用location.state.userId访问状态。

但是对于Typescript,您可能需要强制转换state

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

const location = useLocation();
const locationState = (location.state as {userId? : number});

// get userId
let userId = locationState.userId;

相关问题