【问题标题】:Is it possible to pass props by match in React Link是否可以在 React Link 中通过匹配传递道具
【发布时间】:2020-03-01 18:02:48
【问题描述】:

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

一次按路线路径:-

<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 中,我尝试将 props 读取为:-

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 都能正常工作。 是否可以通过比赛传递道具?或者我该如何解决这个问题?

【问题讨论】:

  • 您确定链接片段吗?你的 prop 链接有 pathname: "/EditProfile",但你的 Route 有 /CreateProfile 路径名!
  • 我还有另一条路线&lt;Route path="/EditProfile" exact component={ProfileForm} /&gt;。所以 /CreateProfile 和 //EditProfile 都指向同一个组件。一旦我创建了一个新的配置文件,另一次我允许编辑现有的配置文件。
  • 您能否提供一个更好的代码示例?因为你可以通过不同的方式通过挑战。

标签: reactjs react-router react-props react-link


【解决方案1】:

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

Link to-object

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

  • 路径名:表示要链接到的路径的字符串。
  • 搜索:查询参数的字符串表示形式。
  • hash:要放入 URL 的哈希值,例如#a 哈希。
  • state:要持续到该位置的状态。

您显然已经为 pathname 变体设置了路由参数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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-18
    • 1970-01-01
    • 2021-09-08
    • 2018-04-27
    • 2021-07-31
    • 2018-12-17
    • 2018-02-28
    • 2019-12-01
    相关资源
    最近更新 更多