微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

React Hook做页面跳转以及携带参数,并且获取携带的值

1.使用useHistory做页面跳转导航

1导入

import { useHistory } from "react-router-dom";

2.使用跳转页

function Home() {  
  const history = useHistory();  
  function handleClick() {    
    history.push("/home");  
  }  
  return (    
    <button type="button" onClick={handleClick}>Go home    </button>  
  );
}

3.使用跳转页面携带参数

import { useHistory } from "react-router-dom";
function HomeButton() {  
  const history = useHistory();  
  let id = 1;
  function handleClick() {    
    history.push({pathname: '/home', state: {id: id}})  
  }  

  return (
    <button type="button" onClick={handleClick}>      Go home    </button>  
  );
}

2.使用useLocation 获取跳转携带的值

4.在home页面获取id值

导入

import { useLocation } from 'react-router-dom';
 const location = useLocation(); //获取跳转页面携带的值  console.log(location.state.id); 3.React useHistory 更新为useNavigate如何传值 1.组件跳转并传值
(1)导入
import { useNavigate } from ‘react-router-dom’;
(2)使用
const navigate = useNavigate();
点击事件中使用

 

 组件“/machine”为已经定义好的路由,state负责传值state:{参数:值}

(3)获取
导入import { useLocation } from ‘react-router-dom’;
使用
let location = useLocation();
let server_id = location.state;

 

 如果是React Router v4,可以使用以下方法

1、使用withRouter组件

import { withRouter } from 'react-router-dom';
const Button = withRouter(({ history }) => (
    <button
        type="button"
        onClick={() => {
            history.push('/new-location');
        }}
    >
        {' '}
        Click Me!{' '}
    </button>
));

2、使用<Route>标签

import { Route } from 'react-router-dom';
const Button = () => (
    <Route
        render={({ history }) => (
            <button
                type="button"
                onClick={() => {
                    history.push('/new-location');
                }}
            >
                {' '}
                Click Me!{' '}
            </button>
        )}
    />
);

3、使用context(这个方法不推荐,context api不是很稳定。)

const Button = (props, context) => (     <button         type="button"         onClick={() => {             context.history.push('/new-location');         }}     >         Click Me!{' '}     </button> ); Button.contextTypes = {     history: React.PropTypes.shape({         push: React.PropTypes.func.isrequired,     }), };

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐