react路由传参及其优缺点
1.params
//注意params形式都需要在路由后面加上一个动态的参数,特点是刷新地址数据依然还在,参数会在url处显示。
<Route path="/user/:name" component={User}></Route>
// 方式一:
<NavLink to="/user/alex">去user页</NavLink>
//方式二:
this.props.history.push({pathname:"/user/"+"alex"})
// 在user页获取参数的方法
this.props.match.params.name
2.search
<Route path="/follow" component={Follow}></Route>
<NavLink to="/follow?number=1212121">去follow</NavLin
//在follow获取参数的方式
this.props.location.search
//注意得到的是带有问好的字符串(?number=1212121)一般用“query-string”插件转化为对象
3.query
//query显示不需要在路由设置里面加动态参数,特点是刷新的话数据就消失了,参数不会显示在url处
<Route path="/detail" component={Detail}></Route>
//方式一:
<NavLink to={{pathname:"/detail",query:{name:"Bob",age:18}}}>去detail</NavLink>
//方式二:
this.props.history.push({pathname:"/detail",query:{name:'小红',age:20}})
//在detail获取参数的方法
this.props.location.query.name
4.state
//state不需要在路由设置动态参数,特点是刷新数据依然保留,参数不会在url处显示
<Route path="/detail" component={Detail}></Route>
this.props.history.push({pathname:"/detail",state:{name:'小红',age:20}})
//在detail中显示数据的方法
{this.props.location.state.name}
{this.props.location.state.age}