reactjs - 是否可以在 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 都能正常工作。是否可以通过比赛传递道具?或者我该如何解决这个问题?
解决方案
您可以通过路径名 (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
推荐阅读
- elasticsearch - 在输出插件logstash中过滤多个主机中的每个输出
- c# - 如何知道列表是否已满
- reactjs - 更新复杂对象
- javascript - 插值不是本机反应的函数
- android - 如何解决“无法访问 androidx.activity.contextaware.ContextAware'”?
- javascript - 时间选择器不应该让我选择比现在更多的时间
- docker - 如何从本地开发机器部署到 Docker Swarm?
- go - 如何在golang ast遍历中从子节点检索父节点?
- android - 关于应用操作默认语言设置
- python - Django:如何为 Forms.ImageField 添加默认位置