Javascript 重定向时传递id或参数

Javascript 重定向时传递id或参数,javascript,reactjs,Javascript,Reactjs,我想在用户单击按钮并被重定向到另一个页面时传递id 我正在使用react路由器,但无法传递id。到目前为止,我尝试了以下代码: <Route path="/editproject/:id" component={EditProject}/> 当用户单击按钮时: if (this.state.switchEdit) { redirect = <Redirect to="/editproject/": {this.state.project.id} /> } re

我想在用户单击按钮并被重定向到另一个页面时传递id

我正在使用react路由器,但无法传递id。到目前为止,我尝试了以下代码:

<Route path="/editproject/:id" component={EditProject}/>

当用户单击按钮时:

if (this.state.switchEdit) {
  redirect = <Redirect to="/editproject/": {this.state.project.id} />
}

render(){
  return (
    { redirect }
  )
}
if(this.state.switchEdit){
重定向=
}
render(){
返回(
{重定向}
)
}
如何传递id(this.state.project.id)?

您可以了解to-concat字符串

<Redirect to={`/editproject/${this.state.project.id}`} />
在您的情况下,您使用的是:id,这就是上面的代码使用
.id

<Route path="/editproject/:id" component={EditProject}/>

您可以使用
模板文本来传递参数

if (this.state.switchEdit){
    redirect=<Redirect to=`/editproject/:${this.state.project.id}` />
}

render(){
    return(
         {redirect}
    )
}
if(this.state.switchEdit){
重定向=
}
render(){
返回(
{重定向}
)
}
并从目标组件中的
match
读取它,如
this.props.match.params.id
,将代码更改为

if (this.state.switchEdit){
        redirect=<Redirect to={`/editproject/:${this.state.project.id`} />
    }

    render(){
               return(
                         {redirect}
              )
           }
if(this.state.switchEdit){
重定向=
}
render(){
返回(
{重定向}
)
}
我使用了模板文本

您可以通过组件的道具访问id

this.props.match.params.id


您可以使用:
props.match.params.whatever\u 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
);
//用户可以使用所有路线道具(匹配、位置和历史记录)
功能用户(道具){
返回Hello{props.match.params.username}!;
}
ReactDOM.render(
,
节点
);

Use:
to={`/editproject/:${this.state.project.id}}}
获得了它,我如何在另一个页面中获得该id?
// 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
);