React router(路由传参)

  • vue里面指向地址的属性叫path,看到网上很多文章,react路由传参指向的属性也叫path,但是:目前react-router-dom:5.1.2指向地址的属性叫做pathname
1、 pathname + search
  • 优点:刷新也在........
  • 缺点:只能传字符串,显式传参,不能传过大的数据,传递数据过多会让地址变的很丑
A页面
<Link to={{pathname: '/setting', search:'id=1'}}>jump --- search</Link>

this.props.history.push({
  pathname: '/setting',
  search: 'a=1'
})
// 取参
B页面
this.props.history.location.search
2、pathname + state
  • 这种形式的传参式隐式的,刷新页面就没有了
  • 和任意属性一致,但是官方应该指定的是这个,因为刷新后location中会存在state: undefined,任意属性则不会
A页面
<Link to={{pathname: '/setting', state:{id:1}}}>jump --- state</Link>
// 取参
B页面
this.props.history.location.state.id
3、pathname + params
  • 配合动态路由传参
  • 优缺点同第一种pathname + search的方式
// 动态路由后面加?表示可选,不加表示必选
<Route path="/setting/:id?" component={Setting}></Route>
A页面
let id = 1;
<Link to={{pathname: `/setting/${id}`}}>jump --- params</Link>
// 取参
B页面
this.props.history.match.params.id
4、replace
<Link to="/setting" replace/>

this.props.history.replace('/setting')
5、react withRouter
  • 高阶组件中的withRouter, 作用是将一个组件包裹进Route里面, 然后react-router的三个对象history, location, match就会被放进这个组件的props属性中.
import React from 'react'
import {
    NavLink,
    withRouter
} from "react-router-dom"

class Nav extends React.Component{
    handleClick = () => {
        // Route 的 三个对象将会被放进来, 对象里面的方法可以被调用
        console.log(this.props);
    }
    render() {
        return (
            <div >
             llaala
            </div>
        );
    }
}

// 导出的是 withRouter(Nav) 函数执行
export default withRouter(Nav)
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容