美文网首页
react-router传递参数的方式

react-router传递参数的方式

作者: 胡_松 | 来源:发表于2019-03-20 11:41 被阅读0次

参考:https://blog.csdn.net/qq_23158083/article/details/68488831

以下方式基于react router版本为3.0.2

一、params方式传递

1、定义路由到detail页面

import {Router,Route,hashHistory} from "react-router";

class App extends React.Component {

    render(){

        return (

            <Router history={hashHistory}>

                <Route path="/detail/:personId" component={Detail}></Route>

            </Router>

        )

    }

}

2、实现跳转的方式

import {Link,hashHistory} from "react-router";

2.1、Link组件实现跳转

<Link to="/detail/33">跳转到详情页面</Link>

2.2、history实现跳转

hashHistory.push("/detail/33")

3、目标页面取值的方式

this.props.params.personId

4、该方式只能通过字符串的方式传递参数,如需传递一个对象过去,需要先将对象转化为字符串(JSON.stringify(json)),在目标页面接收后在转化为对象(JSON.parse(string))

二、query方式传递(类似表单get方法)

1、定义路由到detail页面

<Route path="/detail" component={Detail}></Route>

2、实现跳转的方式

const data={id:33,age:56};

const path={

    pathname:"/detail",

    query:data,

}

<Link to={path}>跳转到详情页面</Link>

hashHistory.push(path)

3、目标页面取值方式

this.props.location.query

4、该方式为在url上明文传递,会导致url很长

三、state方式传递(类似表单post方法)

1、使用方式与query方式传递的一样

2、该方式可以传递任意类型的数据,而且是非明文的方式

相关文章

网友评论

      本文标题:react-router传递参数的方式

      本文链接:https://www.haomeiwen.com/subject/xrfzmqtx.html