gpt4 book ai didi

reactjs - react typescript : Correct type for useLocation() from react-router-dom

转载 作者:行者123 更新时间:2023-12-03 18:13:54 32 4
gpt4 key购买 nike

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

Property 'from' does not exist on type '{} | { from: { pathname: string; }; }'.

添加 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;

最佳答案

您可以创建特定类型或接口(interface)来描述您的位置状态,然后在调用 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;

关于reactjs - react typescript : Correct type for useLocation() from react-router-dom,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61668623/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com