【发布时间】: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路径名! -
我还有另一条路线
<Route path="/EditProfile" exact component={ProfileForm} />。所以 /CreateProfile 和 //EditProfile 都指向同一个组件。一旦我创建了一个新的配置文件,另一次我允许编辑现有的配置文件。 -
您能否提供一个更好的代码示例?因为你可以通过不同的方式通过挑战。
标签: reactjs react-router react-props react-link