【问题标题】:get to state prop from NavLink从 NavLink 获取状态道具
【发布时间】:2021-01-31 10:46:20
【问题描述】:

我有一个对象 - 在我的NavLink 定义的某个组件中聊天。点击ChatsElement - 这是一个链接后,我的页面转到/friends/${chat._id} url。在该 url 下是MoblieConversation 组件,我想在其中使用聊天对象,该对象应通过NavLinkstate 的形式传递。我在哪里读到了这个想法 - 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} />

但我不知道如何在链接/friends/${chat_id} 下的组件中找到这个state 道具。我试过这样的东西,但没有用: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;

【问题讨论】:

  • 您的代码没有意义。据我了解,您想将一些状态传递给您的 ChatsElement?如果是这样,只需导入您想要传递状态的组件并将状态作为道具发送到 ChatsElement 组件。 - 你也需要状态来传递状态,你的代码没有状态。
  • 我还添加了Route 以便更好地理解。我有一个对象 - 在某些组件中聊天,其中定义了我的 NavLink。点击ChatsElement - 这是一个链接后,我的页面转到/friends/${chat._id} url。在该 url 下是 MoblieConversation 组件,我想在其中使用应该通过 NavLink 传递的 chat 对象。我在哪里读到了这个想法 - ui.dev/react-router-v4-pass-props-to-link
  • 我希望我现在解释得更好。

标签: javascript reactjs typescript react-router react-router-dom


【解决方案1】:

假设MobileConversation 直接由Route 组件渲染并接收route props,那么您可以通过location 属性访问路由状态,即props.location.state.chat

const MobileConversation: React.FC<SomeComponentProps> = ({
  location,
  state,
}) => {
  const { id } = useParams<IParams>();
  const { chat } = location.state;
  return <div>{id}</div>;
};

由于这是一个功能组件,并且您已经在使用 react-router-dom 钩子,因此您可以使用 useLocation 钩子。我对打字稿一点也不熟悉,所以希望界面能让你接近你所需要的。

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>;
};

【讨论】:

  • 我还有一个问题。我在这个chat 对象中有一个member 对象和online 状态值。我有时会更改这个online 值。我应该复制member 并在第一个组件渲染时以某些 useEffect 将其变为组件状态吗?
  • @poldeeek 我会说,如果您将其接收到状态,您就可以了,尽管复制进去并没有什么坏处,但是当您通过效果更新它时,您需要应用与任何状态更新相同的模式,将属性浅拷贝到新对象引用中然后更新新对象上的属性。这是为了避免对象/状态突变。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-17
  • 2018-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-05
  • 2015-11-17
相关资源
最近更新 更多