首页 > 解决方案 > 是否可以在 React Link 中通过匹配传递道具

问题描述

我以两种不同的方式将道具传递给同一个组件。

一次通过路线路径:-

<Route path="/CreateProfile/:title" exact component={ProfileForm} />

另一个链接为:

<Table.Cell><Link to={{  // it will land to the same component ProfileForm
pathname:  "/EditProfile",
props: {
profile : profile,
title: "Edit Profile" 
}
}} >Edit Profile</Link></Table.Cell>

在我的 ProfileForm 中,我尝试将道具阅读为:-

useEffect(() => {

  if(props.match.params.title){ // it gives no error. 
    setTitle(props.match.params.title);
  }else if(props.location.props.title){ // gives error .props.title undefiened 
    setTitle(props.location.props.title);
  }
  // if(props.match.params.profile){
  //   setProfile(props.location.state.profile)
  // }
  if(props.location.props.profile){
    setProfile(props.location.props.profile)
    console.log("profile: "+props.location.props.profile)
  }
}

else if(props.location.props.title)当它来自路由器时给出错误。这是意料之中的,因为我通过 Link 设置了道具。我注意到props.match.params.title无论是否设置都不会给出任何错误。所以我希望通过比赛从 Link 传递道具,以便 Route 和 Link 都能正常工作。是否可以通过比赛传递道具?或者我该如何解决这个问题?

标签: reactjsreact-routerreact-propsreact-link

解决方案


您可以通过路径名 (URL) 传递数据,即通过 url 匹配或查询参数,或通过路由状态。

链接到对象

可以具有以下任何属性的对象:

  • 路径名:表示要链接到的路径的字符串。
  • search:查询参数的字符串表示。
  • 散列:要放入 URL 的散列,例如 #a-hash。
  • state:要持续到该位置的状态。

您显然已经为路径名变体设置了路径,路径参数为title.

"/CreateProfile/:title"

您应该简单地构建您的链接以在其中title内置正确的值。

<Link to={{ pathname: "/CreateProfile/<some title value>" }} >
  Create Profile
</Link>

从这里您只需match.params.title按照正确的方式访问路线。

现在,在编辑配置文件路由的情况下,"/EditProfile"有,OFC,没有路由匹配参数(也没有查询参数),所以正确的方法是使用路由状态。

<Link
  to={{
    pathname: "/EditProfile",
    state: {
      profile,
      title: 'Edit Title',
    },
  }}
>
  Edit Profile
</Link>

并从history对象正确访问路由状态

useEffect(() => {
  const { history, match } = props;

  if (match.params.title) { 
    setTitle(match.params.title);
  } else if (history.location.state.title){
    setTitle(history.location.state.title);
  }

  if (history.location.state.profile) {
    setProfile(history.location.state.profile)
    console.log("profile: ", history.location.state.profile)
  }
}

然而,关于路由状态的建议的话,对象路径并不总是保证存在(即被定义)props.history.location到您正在访问的最终值,因此需要保护以防止“访问未定义的错误”错误。

 // state may not be defined depending on which route the app took to get to the page
history.location.state && history.location.state.title

推荐阅读