react中link參數傳遞以及url亂碼解決


react中link參數傳遞以及url亂碼解決

1.可以通過動態路由的方式進行參數傳遞

​ 傳遞:path="/acticle/:id"

 render() {
        return (
            <div>
                <Link to="/acticle/1?"> 文章一</Link>
                <Link to="/acticle/2"> 文章二</Link>
                <Route path="/acticle/:id" component={ArticleDetail}></Route>
            </div>
        )
    }

接收參數:this.props.match.params.id

2.可以通過query進行傳參

​ 傳遞:path="/acticle?title=文章一"

export default class Acticle extends Component {
    render() {
        return (
            <div>
                <Link to="/acticle/1?title=文章1"> 文章一</Link>
                <Link to="/acticle/2"> 文章二</Link>
                <Route path="/acticle/:id" component={ArticleDetail}></Route>
            </div>
        )
    }
}

​ 接收參數:Detail組件內部可以通過 this.props.location.search可以獲取到 “?title=文章一”

url亂碼解決

export default class Acticle extends Component {
    
    render() {
        console.log(this.props.location.search)
        var str =this.props.location.search
        var start = str.indexOf("=")
        var newStr = str.substr(start+1,str.length)
        console.log(decodeURI())
        return (
            <div>
                <h2>{decodeURI(newStr)}</h2>
                文章
            </div>
        )
    }
}

3.可以通過state進行隱式傳參(同query差不多,只是屬性不一樣,而且state傳的參數是加密的,query傳的參數是公開的,在地址欄)

傳遞: to={{pathname:'/acticle/2',state:{title:'文章2'}}}

export default class Acticle extends Component {
    render() {
        return (
            <div>
                <Link to={{pathname:'/acticle/1',state:{title:'qw'}}}> 文章一</Link>
                <Link to="/acticle/2"> 文章二</Link>
                <Route path="/acticle/:id" component={ArticleDetail}></Route>
            </div>
        )
    }
}

​ 接收參數:Detail組件內部可以通過 this.props.location.state.title可以獲取到

注意:通過state傳參刷新有時候參數會消失,不曉得為什么?有知道的歡迎解答


免責聲明!

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



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