![](/img/trans.png)
[英]How to pass props/params/state to a Route with Link in React Router 5.2.0?
[英]Pass params with Link react
我在'/'
路由上有一个索引组件,在那个组件中有一个Link
。 当我单击链接时,确实会重新路由到/search
,但是如何通过该链接传递一些参数,并将其放入/search
路由中呈现的组件中。
到目前为止,这是我尝试过的:
链接到索引组件内部:
<Link to={{ pathname: '/search', query: this.state.status }}>
Search
</Link>
匹配/search
的路由
<Route exact path="/search" component={Search}/>
Search
组件
class Search extends React.Component {
constructor(props){
super(props);
}
render() {
console.log("Props are: ");
console.log(this.props);
return (
<div className="col-xs-12 text-center tweet-background">
<h1>{this.props.query}</h1>
</div>
)
}
}
但不幸的是, props
参数只有:
Object {match: Object, location: Object, history: Object, staticContext: undefined}
我是否在Link内部传递了参数? 如果没有,我该如何实现?
为了让您了解我要实现的目标,请考虑一下Google搜索。 单击Search
,它将带您到带有参数的另一个组件。
编辑:
为简单起见,由于大多数问题都与索引组件的状态有关,因此将查询更改为query: { name: 'ryan' }
。
除了将query
替换为search
,您还可以按以下方式访问query
:
this.props.location.query
鉴于:
<Link to={{ pathname: '/search', query: this.state.status }}> Search </Link>
React-router注入location
属性,该属性是一个对象,具有一些属性,包括存储URL的查询字符串部分的search
,因此请尝试使用:
this.props.location.search
如果有人遇到相同的问题,请将query
替换为search
。
<Link to={{ pathname: '/search', query: this.state.status }}>
Search
</Link>
会变成这个
<Link to={{ pathname: '/search', search: this.state.status }}>
Search
</Link>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.