关于react.js:react-路由传参及其区别

7次阅读

共计 1131 个字符,预计需要花费 3 分钟才能阅读完成。

1.params

<Route path='/path/:name' component={Path}/>
<link to="/path/2">xxx</Link>
this.props.history.push({pathname:"/path/" + name});
读取参数用:this.props.match.params.name

劣势:刷新地址栏,参数仍然存在
毛病: 只能传字符串,并且,如果传的值太多的话,url 会变得长而俊俏。

2.query

<Route path='/query' component={Query}/>
<Link to={{path : '/query' , query : { name : 'sunny'}}}>
this.props.history.push({pathname:"/query",query: { name : 'sunny'}});
读取参数用: this.props.location.query.name

劣势:传参优雅,传递参数可传对象;
毛病:刷新地址栏,参数失落

3.state

<Route path='/sort' component={Sort}/>
<Link to={{path : '/sort' , state : { name : 'sunny'}}}> 
this.props.history.push({pathname:"/sort",state : { name : 'sunny'}});
读取参数用: this.props.location.query.state 

优缺点同 query

4.search

<Route path='/web/departManange' component={DepartManange}/>
<link to="web/departManange?tenantId=12121212">xxx</Link>
this.props.history.push({pathname:"/web/departManange?tenantId" + row.tenantId});
读取参数用: this.props.location.search

优缺点同 params

react Hooks 中获取路由参数的形式:

1. 通过 hooks 钩子函数

import {useHistory,useLocation,useParams,useMatch} from 'react-router-dom';
let history = useHistory();
history.push('/')

2. 通过函数 props 参数

function Home(props) {const location = useLocation();
    return (
        <div className='home'>
            <Banner />
        </div>
    )
}
正文完
 0