gpt4 book ai didi

reactjs - 我应该为对象 rest Prop 声明什么类型?

转载 作者:搜寻专家 更新时间:2023-10-30 21:34:54 25 4
gpt4 key购买 nike

这是一个来自 react-router 的例子,说明如何为 protected 路由添加一个组件:

function PrivateRoute({ component: Component, ...rest }) {
return (
<Route
{...rest}
render={props =>
fakeAuth.isAuthenticated ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: "/login",
state: { from: props.location }
}}
/>
)
}
/>
);
}

https://reacttraining.com/react-router/web/example/auth-workflow

我尝试在我的 Typescript 项目中实现此功能,以上面的示例为灵感。

import * as React from 'react';
import {
Route,
Redirect,
} from 'react-router-dom';

interface PrivateRouteProps {
component: React.Component; // passed as prop
isSignedIn: boolean; // injected as prop by redux
location: Location;
}

const PrivateRoute = (props: PrivateRouteProps) => {
const { component: Component, isSignedIn, location } = props;

return (
<Route
{...rest}
render={(routeProps) =>
isSignedIn ? (
<Component {...routeProps} />
) : (
<Redirect
to={{
pathname: '/signin',
state: { from: location }
}}
/>
)
}
/>
);
};

export default PrivateRoute;

我得到以下错误

[ts] Cannot find name 'rest'.
any

[ts] JSX element type 'Component' does not have any construct or call signatures.
const Component: React.Component<{}, {}, any>

最佳答案

1) 你还没有从你的解构运算符中提取剩余的 Prop ,要获得其余的 Prop ,你需要这个:

const { component: Component, isSignedIn, location, ...rest } = props;

2) Component 不是你想的那样,它是类元素构造的接口(interface),但你用它来定义类型。如果您希望将其强制执行为元素,则需要使用 JSX.Element

最终你应该得到:

import * as React from 'react';
import {
Route,
Redirect,
} from 'react-router-dom';

interface PrivateRouteProps {
component: JSX.Element; // passed as prop
isSignedIn: boolean; // injected as prop by redux
location: Location;
}

const PrivateRoute = (props: PrivateRouteProps) => {
const { component, isSignedIn, location, ...rest } = props;

return (
<Route
{...rest}
render={(routeProps) =>
isSignedIn ? (
<Component {...routeProps} />
) : (
<Redirect
to={{
pathname: '/signin',
state: { from: location }
}}
/>
)
}
/>
);
};

export default PrivateRoute;

关于reactjs - 我应该为对象 rest Prop 声明什么类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53100690/

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