params 传参
params 传参(刷新页面后参数不消失,参数会在地址栏显示)
路由页面:
1
| <Route path="/demo/:id" component={Demo}></Route> // 注意要配置 /:id
|
路由跳转并传递参数:
- 链接方式:
1 2
| <Link to={'/demo/'+'6'}>XX</Link> <Link to={{pathname:'/demo/'+'6'}}>XX</Link>
|
- js 方式:
1 2
| this.props.history.push("/demo/" + "6"); this.props.history.push({ pathname: "/demo/" + "6" });
|
获取参数:
1
| this.props.match.params.id;
|
params 传参(多个动态参数)
1 2 3 4
| state = { id: 88, name: "Jack" };
|
路由页面:
1
| <Route path="/demo/:id/:name" component={Demo}></Route>
|
路由跳转并传递参数:
- 链接方式:
1
| <Link to={{ pathname: `/demo/${this.state.id}/${this.state.name}` }}>XX</Link>
|
- js 方式:
1 2 3
| this.props.history.push({ pathname: `/demo/${this.state.id}/${this.state.name}` });
|
获取参数:
1
| this.props.match.params;
|
query 传参
刷新页面后参数消失
路由页面:
1
| <Route path="/demo" component={Demo}></Route> // 无需配置
|
路由跳转并传递参数:
- 链接方式:
1
| <Link to={{ pathname: "/demo", query: { id: 22, name: "dahuang" } }}>XX</Link>
|
- js 方式:
1 2 3 4
| this.props.history.push({ pathname: "/demo", query: { id: 22, name: "dahuang" } });
|
获取参数:
1
| this.props.location.query.name;
|
state 传参
刷新页面后参数不消失,state 传的参数是加密的,比 query 传参好用
注:state 传参的方式只支持 Browserrouter 路由
,不支持 hashrouter
路由页面:
1
| <Route path="/demo" component={Demo}></Route> //无需配置
|
路由跳转并传递参数:
- 链接方式:
1
| <Link to={{ pathname: "/demo", state: { id: 12, name: "dahuang" } }}>XX</Link>
|
- js 方式:
1 2 3 4
| this.props.history.push({ pathname: "/demo", state: { id: 12, name: "dahuang" } });
|
获取参数:
1
| this.props.location.state.name;
|