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,
    }),
};

 


免責聲明!

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



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