4

React报错之useNavigate() may be used only in context of Router - chuckQu

 2 years ago
source link: https://www.cnblogs.com/chuckQu/p/16564272.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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测试库时遇到错误,解决办法也是一样的。你必须把使用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)就相当于按下了后退按钮。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK