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)
您可以使用“历史”中的位置。
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)
归档时间: |
|
查看次数: |
10594 次 |
最近记录: |