[英]React router, pass props with Link
Im using React Router to navigate to a page in my app like this: 我使用React Router导航到我的应用程序中的页面,如下所示:
<Link to={`/single/${this.props.data.pageId}`} params={{singleId: 1}}>GotoPage!</Link>
This works fine but I would also like to pass an additional property to the new page. 这工作正常,但我还想将其他属性传递给新页面。
When rendering a component without using Link I would do something like: 在不使用Link的情况下渲染组件时,我会执行以下操作:
<MyComponent myProp={this.props.data}/>
I have tried passing myProp={this.props.data}
along in params like this: 我试过像这样在params中传递
myProp={this.props.data}
:
<Link to={`/single/${this.props.data.pageId}`} params={{singleId: 1, myProp={this.props.data}}}>GotoPage!</Link>
But it does not seem to work as myProp is undefined on the new page as oppose to pageId which I can get like: 但它似乎不起作用,因为myProp在新页面上未定义,与pageId相反,我可以得到:
this.props.params.pageId;
Am I not supposed to be able to pass non-route related parameters with Link
? 我不应该能够通过
Link
传递非路由相关参数吗?
In the documentation for Link
and also the source, there's no mention of it taking param
. 在
Link
的文档和源代码中,没有提到它采用param
。 But I get what you're trying to do. 但是我得到了你想要做的事情。
Instead of hard-coding routes, may I recommend using react-router's history function router.push()
. 我建议使用react-router的历史记录功能
router.push()
,而不是硬编码路由。 Do something like this instead: 做这样的事情:
class Foo extends React.Component {
...
const handleNewRoute = () => {
let { pageId } = this.props.data
let singleId = '1'
this.context.router.push({ // use push
pathname: `/single/${pageId}`,
query: { singleId }
})
}
render() {
return (
<button onLeftClick={this.handleNewRoute} />
)
}
}
By the way, in React/JSX, something like ...{{singleId: 1, myProp={this.props.data}}}...
should be <Link...foobar={{singleId: 1, myProp: this.props.data}}>
. 顺便说一句,在React / JSX中,类似
...{{singleId: 1, myProp={this.props.data}}}...
应该是<Link...foobar={{singleId: 1, myProp: this.props.data}}>
。 The former syntax is wrong. 前一种语法错了。
I think the better way to get the additional data is an ajax. 我认为获得额外数据的更好方法是ajax。
But if you want your way to do this,I check the api of Link and I find a query property. 但是如果你想要你的方法,我检查链接的API,我找到一个查询属性。
query:
An object of key:value pairs to be stringified.
so you can use this to pass a object of key:value to the next route,but this object will be stringified and passed though the url I think.I prefer an ajax for this. 所以你可以使用它来将key:value的对象传递给下一个路由,但是这个对象将被字符串化并通过我认为的url传递。我更喜欢ajax。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.