我想在用户单击按钮并重定向到另一个页面时传递ID。
我正在使用React Router,但无法传递ID。到目前为止,我尝试了以下代码:
<Route path="/editproject/:id" component={EditProject}/>
当用户点击按钮时:
if (this.state.switchEdit) {
redirect = <Redirect to="/editproject/": {this.state.project.id} />
}
render(){
return (
{ redirect }
)
}
如何传递ID(this.state.project.id)?
答案 0 :(得分:1)
您可以了解有关Template Literals连接字符串的信息。
<Redirect to={`/editproject/${this.state.project.id}`} />
要取回参数,可以使用该代码从参数中检索。
this.props.match.params.id
在您的情况下,您使用的是:id ,这就是上面的代码使用.id
<Route path="/editproject/:id" component={EditProject}/>
答案 1 :(得分:0)
您可以使用template literals
来传递参数
if (this.state.switchEdit){
redirect=<Redirect to=`/editproject/:${this.state.project.id}` />
}
render(){
return(
{redirect}
)
}
并从match
中读取,就像目标组件中的this.props.match.params.id
答案 2 :(得分:0)
将您的代码更改为
if (this.state.switchEdit){
redirect=<Redirect to={`/editproject/:${this.state.project.id`} />
}
render(){
return(
{redirect}
)
}
我利用模板文字
您可以通过组件的道具访问ID
this.props.match.params.id
答案 3 :(得分:0)
您可以使用props.match.params.whatever_was_passedinURL
检查以下示例...
// All route props (match, location and history) are available to User
function User(props) {
return <h1>Hello {props.match.params.username}!</h1>;
}
ReactDOM.render(
<Router>
<Route path="/user/:username" component={User} />
</Router>,
node
);