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();
點擊事件中使用
(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,
}),
};
