React報錯之useNavigate() may be used only in context of Router

正文從這開始~

總覽

當我們嘗試在react router的Router上下文外部使用useNavigate 鉤子時,會產生”useNavigate() may be used only in the context of a Router component”警告。為了解決該問題,只在Router上下文中使用useNavigate 鉤子。

usenavigate-may-be-used-only-in-the-context-of-router.png

下面是一個在index.js文件中將React應用包裹到Router中的例子。

// index.js
import {createRoot} from 'react-dom/client';
import App from './App';
import {BrowserRouter as Router} from 'react-router-dom';

const rootElement = document.getElementById('root');
const root = createRoot(rootElement);

// 👇️ wrap App in Router

root.render(
  <Router>
    <App />
  </Router>
);

useNavigate

現在,你可以在App.js文件中使用useNavigate鉤子。

// App.js
import React from 'react';
import {
  useNavigate,
} from 'react-router-dom';

export default function App() {
  const navigate = useNavigate();

  const handleClick = () => {
    // 👇️ navigate programmatically
    navigate('/about');
  };

  return (
    <div>
      <button onClick={handleClick}>Navigate to About</button>
    </div>
  );
}

會發生錯誤是因為useNavigate鉤子使用了Router組件提供的上下文,所以它必須嵌套在Router裡面。

用Router組件包裹你的React應用程式的最佳位置是在你的index.js文件中,因為那是你的React應用程式的入口點。

一旦你的整個應用都被Router組件所包裹,你可以隨時隨地的在組件中使用react router所提供的鉤子。

Jest

如果你在使用Jest測試庫時遇到錯誤,解決辦法也是一樣的。你必須把使用useNavigate鉤子的組件包裹在一個Router中。

// App.test.js
import {render} from '@testing-library/react';
import App from './App';
import {BrowserRouter as Router} from 'react-router-dom';

// 👇️ wrap component that uses useNavigate in Router

test('renders react component', async () => {
  render(
    <Router>
      <App />
    </Router>,
  );

  // your tests...
});

useNavigate鉤子返回一個函數,讓我們以編程方式進行路由跳轉,例如在一個表單提交後。

我們傳遞給navigate函數的參數與<Link to="/about">組件上的to屬性相同。

replace

如果你想使用相當於history.replace()的方法,請向navigate函數傳遞一個配置參數。

// App.js
import {useNavigate} from 'react-router-dom';

export default function App() {
  const navigate = useNavigate();

  const handleClick = () => {
    // 👇️ replace set to true
    navigate('/about', {replace: true});
  };

  return (
    <div>
      <button onClick={handleClick}>Navigate to About</button>
    </div>
  );
}

當在配置對象中將replace屬性的值設置為true時,瀏覽器歷史堆棧中的當前條目會被新的條目所替換。

換句話說,由這種方式導航到新的路由,不會在瀏覽器歷史堆棧中推入新的條目。因此如果用戶點擊了回退按鈕,並不會導航到上一個頁面。

這是很有用的。比如說,當用戶登錄後,你不想讓用戶能夠點擊回退按鈕,再次回到登錄頁面。或者說,有一個路由要重定向到另一個頁面,你不想讓用戶點擊回退按鈕從而再次重定向。

你也可以使用數值調用navigate 函數,實現從歷史堆棧中回退的效果。例如,navigate(-1)就相當於按下了後退按鈕。