Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

react跨页面传值有哪些方法 #60

Open
yuanyinghao1 opened this issue Jul 6, 2021 · 1 comment
Open

react跨页面传值有哪些方法 #60

yuanyinghao1 opened this issue Jul 6, 2021 · 1 comment

Comments

@yuanyinghao1
Copy link

No description provided.

@yuanyinghao1
Copy link
Author

一.props.params

<Route>指定一个path,然后指定通配符可以携带参数到指定的path:
首先定义路由到UserPage页面:
import { Router,Route,hashHistory} from 'react-router';
1. class App extends React.Component {
2.   render() {
3.     return (
4.         <Router history={hashHistory}>
5.             <Route path='/user/:name' component={UserPage}></Route>
6.         </Router>
7.     )
8.   }
9. }
上面指定参数一个参数name
使用:
import {Link,hashHistory} from 'react-router';
1.Link组件实现跳转:
<Link to="/user/sam">用户</Link>
2.history跳转:
hashHistory.push("/user/sam");
当页面跳转到UserPage页面之后,取出传过来的值:
1. export default class UserPage extends React.Component{
2.     constructor(props){
3.         super(props);
4.     }
5.     render(){
6.         return(<div>this.props.params.name</div>)
7.     }
8. }
上面的方法可以传递一个或多个值,但是每个值的类型都是字符串,没法传递一个对象,如果传递的话可以将json对象转换为字符串,然后传递过去,传递过去之后再将json字符串转换为对象将数据取出来
如:定义路由:
<Route path='/user/:data' component={UserPage}></Route>
使用:
var data = {id:3,name:sam,age:36};
data = JSON.stringify(data);
var path = `/user/${data}`;
1.<Link to={path}>用户</Link>
2.hashHistory.push(path);
获取数据:
var data = JSON.parse(this.props.params.data);
var {id,name,age} = data;
通过这种方式跳转到UserPage页面时只能通过传递字符串来传递参数

二.query

query方式使用很简单,类似于表单中的get方法,传递参数为明文:
首先定义路由:
<Route path='/user' component={UserPage}></Route>
使用:
var data = {id:3,name:sam,age:36};
var path = {
  pathname:'/user',
  query:data,
}
1.<Link to={path}>用户</Link>
2.hashHistory.push(path);
获取数据:
var data = this.props.location.query;
var {id,name,age} = data;

三.state

state方式类似于post方式,使用方式和query类似,
首先定义路由:
<Route path='/user' component={UserPage}></Route>
使用:
var data = {id:3,name:sam,age:36};
var path = {
  pathname:'/user',
  state:data,
}
1.<Link to={path}>用户</Link>
2.hashHistory.push(path);
获取数据:
var data = this.props.location.state;
var {id,name,age} = data;
state方式依然可以传递任意类型的数据,而且可以不以明文方式传输。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant