想要使用typescript将属性添加到react路由器中的状态对象



我渲染了一堵卡片墙,当用户点击卡片时,我通过react路由器将他重定向到卡片上,并只渲染这个特定的卡片。要做到这一点,我需要在组件之间传递道具。我创建了一个组件,该组件要么使用NavLink(墙元素(渲染,要么不使用(solo Card(渲染;

为了传递道具,我决定使用react路由器状态对象。这是有效的,但因为TS非常爱我,它告诉我,这样做可能不是一个好主意,因为状态中的属性可能是未定义的。

所以很明显,我需要告诉TS这些属性是存在的。我创建了一个界面Match,但不知道在哪里添加。

它的一个组成部分是墙或卡片元素。

import {memo} from "react";
import {Picture} from "./../Picture/Picture";
import {NavLink} from "react-router-dom";
import {
RouteComponentProps,
StaticRouterProps,
} from "react-router-dom";
import "./card.scss";

interface CompProps
extends Partial<RouteComponentProps> {
userId?: string;
id?: number;
title?: string;
body?: string;
userName?: string;
clItem: string;
cardLink: string;
clTitle: string;
clBody: string;
clUser: string;
linkOptional?: boolean;
}
// interface Match {
//   location: {
//     state: {
//       userId: string;
//       body: string;
//       title: string;
//     };
//   };
// }
export const Card: React.FC<CompProps> = memo(
({
userId,
id,
title,
body,
clItem,
cardLink,
clTitle,
clBody,
clUser,
userName,
match,
history,
linkOptional,
}): JSX.Element => {
return (
<>
{!linkOptional ? (
<NavLink
to={{
pathname: `/post/${id}/${userName}`,
state: {
userId: userId,
title: title,
body: body,
},
}}
className={cardLink}>
<section className={clItem}>
<p className={clUser}>{userId}</p>
<Picture
mediasize="1000"
clPicture="picture_item"
/>
<p className={clTitle}>{title}</p>
<p className={clBody}>{body}</p>
</section>
</NavLink>
) : (
<section className={clItem}>
{console.log(match, history)}
<p
className={
history.location.state.userId
}></p>
<Picture
mediasize="1000"
clPicture="picture_item"
/>
<p className={clTitle}>{title}</p>
<p className={clBody}>{body}</p>
</section>
)}
</>
);
}
);

这是一个错误,请参阅:

/media/darek/Seagate Expansion Drive/WebstormProjects/hsbc/src/components/Card/Card.tsx
TypeScript error in /media/darek/Seagate Expansion Drive/WebstormProjects/hsbc/src/components/Card/Card.tsx(80,17):
Object is possibly 'undefined'.  TS2532
78 |             <p
79 |               className={
> 80 |                 history.location.state.userId
|                 ^
81 |               }></p>
82 |             <Picture
83 |               mediasize="1000"

我使用useLocation钩子解决了它;

**interface Match {
userId: string;
body: string;
title: string;
}**
interface CompProps {
clItem: string;
cardSolo: string;
clTitle: string;
clBody: string;
clUser: string;
}
export const CardNoLink: React.FC<CompProps> = ({
clItem,
cardSolo,
clTitle,
clBody,
clUser,
}): JSX.Element => {
**const {state} = useLocation<Match>();**
return (
<section className={`${clItem} ${cardSolo}`}>
**{console.log(state.userId)}**

这使我可以将属性添加到State。

最新更新