[英]get to state prop from NavLink
I have an object - chat in some component where is defined my NavLink
.我在定义了我的
NavLink
某个组件中有一个对象聊天。 After click on ChatsElement
- which is a link, my page go to /friends/${chat._id}
url.点击
ChatsElement
- 这是一个链接后,我的页面转到/friends/${chat._id}
网址。 Under that url is MoblieConversation
component, where I want to use chat object which should be passed as state
via NavLink
.在该 url 下是
MoblieConversation
组件,我想在其中使用聊天对象,该对象应该通过NavLink
作为state
NavLink
。 There is where I read about this idea - enter link description here我在那里读到了这个想法 -在此处输入链接描述
<NavLink
to={{ pathname: `/friends/${chat._id}`, state: chat }}
key={chat._id}
>
<ChatsElement chat={chat} />
</NavLink>
. .
<Route path="/friends/:id" component={MobileConversation} />
But I don't know how to get to this state
prop in component which is under link /friends/${chat_id}
.但我不知道如何在链接
/friends/${chat_id}
下的组件中访问此state
道具。 I tried something like this, but didn't work :v我试过这样的东西,但没有用:v
import React from "react";
import { useParams, RouteComponentProps } from "react-router";
import styles from "./mobileConversation.module.scss";
interface IParams {
id: string;
}
type SomeComponentProps = RouteComponentProps;
const MobileConversation: React.FC<SomeComponentProps> = ({ state }) => {
const { id } = useParams<IParams>();
const chat = location.state;
return <div>{id}</div>;
};
export default MobileConversation;
Assuming MobileConversation
is directly rendered by a Route
component and is receiving route props then you can access the route state via the location
prop, ie props.location.state.chat
.假设
MobileConversation
由Route
组件直接呈现并且正在接收路由道具,那么您可以通过location
道具访问路由状态,即props.location.state.chat
。
const MobileConversation: React.FC<SomeComponentProps> = ({
location,
state,
}) => {
const { id } = useParams<IParams>();
const { chat } = location.state;
return <div>{id}</div>;
};
Since this is a functional component and you are already using react-router-dom hooks, you can use the useLocation hook.由于这是一个功能组件,并且您已经在使用 react-router-dom 钩子,因此您可以使用useLocation钩子。 I'm not very familiar with typescript at all, so hopefully the interface gets you close to what you need.
我对打字稿一点也不熟悉,所以希望界面能让你接近你所需要的。
interface ILocation {
state: any;
}
const MobileConversation: React.FC<SomeComponentProps> = ({ state }) => {
const { id } = useParams<IParams>();
const location = useLocation<ILocation>();
const { chat } = location.state;
return <div>{id}</div>;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.