React-Router useNavigate()

5,962 阅读1分钟

1 . what ?

useNavigate() 钩子在 React Router v6 中引入,以取代 useHistory() 钩子。

  • 在早期版本中,useHistory() 钩子访问 React Router 历史对象,并使用 push 或 replace 方法导航到其他路由器。它有助于转到特定的URL,前进或后退页面。在更新的版本中,React Router的新导航API提供了一个useNavigate()钩子,这是一个强制性版本,用于以更好的兼容性执行导航操作。

2 . 导入

import { Link, useNavigate } from 'react-router-dom'

3 . 使用

  //js写法
  let navigate = useNavigate();
  function handleClick() {
    navigate("/home");
  }
  //组件写法
  function App() {
     return <Navigate to="/home" replace state={state} />;
  }
  //替代原有的go goBack和goForward
 <button onClick={() => navigate(-2)}>
    Go 2 pages back
  </button>
  <button onClick={() => navigate(-1)}>Go back</button>
  <button onClick={() => navigate(1)}>
    Go forward
  </button>
  <button onClick={() => navigate(2)}>
    Go 2 pages forward
  </button>