Hel*_*Out 7 types typescript reactjs react-router
我不太明白这一点。我搜索了 stackoverflow 和 github,我尝试的解决方案之一是添加一个泛型,但我Expected 0 type arguments, but got 1.在useLocation<LocationState>下面收到此错误,这是我的代码。我遇到的问题是将类型设置为{searchvalue}但其类型未知。任何帮助将不胜感激。
import React from "react";
import { useLocation } from "react-router-dom";
interface SearchResultsProps {}
interface LocationState {
serachValue: string
}
export const SearchResults: React.FC<SearchResultsProps> = ({}) => {
const location = useLocation<LocationState>();
const {searchValue} = location.state
return <div>Results Page</div>;
Run Code Online (Sandbox Code Playgroud)
useLocation以下是该钩子文档的链接react-router-dom:https://reactrouter.com/docs/en/v6/api#uselocation
它将函数签名定义为:
Run Code Online (Sandbox Code Playgroud)declare function useLocation(): Location; interface Location extends Path { state: unknown; key: Key; }
您可以看到它location.state的类型为unknown,因此如果您已将数据推送到历史状态,并且希望以类型安全的方式访问它,您可以断言已推送到状态的数据类型,如下所示:
const location = useLocation();
const {serachValue} = location.state as LocationState;
Run Code Online (Sandbox Code Playgroud)
这是一个完整的示例:
import {default as React, type ReactElement} from 'react';
import {useLocation} from 'react-router-dom';
type EmptyObject = Record<never, never>;
type LocationState = { serachValue: string; };
function SearchResults (props: EmptyObject): ReactElement {
const location = useLocation();
const {serachValue} = location.state as LocationState;
// ^^^^^^^^^^^
// is now type 'string'
return (<div>Results Page</div>);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15267 次 |
| 最近记录: |