params传参
import React from 'react'
import { Route, NavLink} from 'react-router-dom'
class AppRouter extends React.Component {
constructor(props) {
super(props);
this.state = {
id: 1,
name: '呵呵'
}
}
render() {
return (
<div>
<ul>
{/* params传参 */}
<li><NavLink activeClassName="active" to={`/index/${this.state.id}/${this.state.name}`}>首页</NavLink></li>
</ul>
<Route path="/index/:id/:name" component={Index} />
</div>
);
}
}
function Index(props) {
console.log(props);
const {id,name } = props.match.params
return (
<div>
<span>id: {id}</span>
<span>name: {name}</span>
</div>
)
}
export default AppRouter;
search传参
import React from 'react'
import { Route, NavLink } from 'react-router-dom'
import qs from 'querystring'
class AppRouter extends React.Component {
constructor(props) {
super(props);
this.state = {
id: 1,
name: '呵呵'
}
}
render() {
return (
<div>
<ul>
{/* params传参 */}
<li><NavLink activeClassName="active" to={`/index?id=${this.state.id}&name=${this.state.name}`}>首页</NavLink></li>
</ul>
<Route path="/index" component={Index} />
</div>
);
}
}
function Index(props) {
console.log(props);
const { id, name } = qs.parse(props.location.search.slice(1))
return (
<div>
<span>id: {id}</span>
<span>name: {name}</span>
</div>
)
}
export default AppRouter;
state 传参
import React from 'react'
import { Route, NavLink } from 'react-router-dom'
class AppRouter extends React.Component {
constructor(props) {
super(props);
this.state = {
id: 1,
name: '呵呵'
}
}
render() {
return (
<div>
<ul>
{/* state传参 */}
<li><NavLink activeClassName="active" to={{ pathname: '/index', state: { id: this.state.id, name: this.state.name } }}>关于</NavLink></li>
</ul>
<Route path="/index" component={Index} />
</div>
);
}
}
function Index(props) {
console.log(props);
const { id, name } = props.location.state
return (
<div>
<span>id: {id}</span>
<span>name: {name}</span>
</div>
)
}
export default AppRouter;
总结
-
params参数
路由链接(携带参数):<NavLink activeClassName="active" to={/index/${this.state.id}/${this.state.name}
}>首页</NavLink>
注册路由(声明接收):<Route path="/index/:id/:name" component={Index} />
接收参数:props.match.params
-
search参数
路由链接(携带参数):<NavLink activeClassName="active" to={/index?id=${this.state.id}&name=${this.state.name}
}>首页</NavLink>
注册路由(无需声明,正常注册即可):<Route path="/index" component={Index} />
接收参数:props.location.search
备注:获取到的search是urlencoded编码字符串,需要借助querystring解析
-
state参数
路山链接(携带参数):<NavLink activeClassName="active" to={{ pathname: '/index', state: { id: this.state.id, name: this.state.name } }}>关于</NavLink>
注册路山(无需声明,正常注册即可):<Route path="/index" component={Index} />
接收参数:props.location.state