React頁面跳轉傳參


來自 https://www.jianshu.com/p/02c1cf54a5df 侵刪

  1. this.props.location.query:
    1)路由注冊
    <Route path=' /target ' component={TargetPage}></Route>
    2)發起跳轉頁面
    html方式:
    <Link to={{ path : ' /target ' , query : { id : '6666' }} >XXXX</Link>
    js方式:
    this.props.history.push({ pathname : '/target' , query : { id : '6666' }})
    3)接受跳轉頁面
    const id=this.props.location.query.id;
    就可以接受到傳遞過來的參數(id)

  2. this.props.location.state:同query差不多,但是state傳的參數是加密的,query傳的參數是公開的,會在地址欄中顯示;
    <Route path=' /target ' component={TargetPage}></Route>
    2)發起跳轉頁面
    html方式:
    <Link to={{ path : ' /target ' , state : { id : '6666' }} >XXXX</Link>
    js方式:
    this.props.history.push({ pathname : '/target' , state : { id : '6666' }})
    3)接受跳轉頁面
    const id=this.props.location.state.id;
    就可以接受到傳遞過來的參數(id)

  3. this.props.location.match:
    1)路由注冊
    <Route path=' /target/:id ' component={TargetPage}></Route>
    2)發起跳轉頁面
    html方式:
    <Link to={ ' /target/ ' + ' 6666 ' } >XXXX</Link>
    js方式:
    this.props.history.push( '/target/'+'6666' )
    3)接受跳轉頁面
    const id=this.props.location.macth;
    就可以接受到傳遞過來的參數(id)

  4. this.props.location.search:
    1)路由注冊
    <Switch>
    <Route path=' /target ' component={TargetPage}></Route>
    ……
    </Switch>

2)發起跳轉頁面
html方式:
<Link to={path : ' /target?id=6666 ' } >XXXX</Link>
js方式:
this.props.history.push('/target?id=6666')
3)接受跳轉頁面
相當於解析地址信息
const id= getQueryVariable(this.props.location.search, 'id');
或者
const id= getQueryVariable(window.location.search,‘id');
就可以接受到傳遞過來的參數(id)

function getQueryVariable(searchIn, variable) { if (!searchIn || !variable) { return null; } const query = searchIn.substring(1); const vars = query.split("&"); for (let i = 0; i < vars.length; i++) { const pair = vars[i].split("="); if (pair[0] === variable) { return pair[1]; } } return null; }


作者:周_0717
鏈接:https://www.jianshu.com/p/02c1cf54a5df
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM