简体   繁体   English

错误:useHref() 只能在 a 的上下文中使用<router>成分。 当我直接将 url 作为 localhost:3000/experiences 时,它会起作用</router>

[英]Error: useHref() may be used only in the context of a <Router> component. It works when I directly put the url as localhost:3000/experiences

I have a navbar that is rendered in every route while the route changes on click.我有一个导航栏,它在点击时更改路线时在每条路线中呈现。

./components/navbar.jsx ./components/navbar.jsx

import React, { Component } from 'react';
import '../App.css';
import { Link } from 'react-router-dom';



class Navbar extends Component {
    constructor(props) {
        super(props);
        this.state = {};
    }
    render() {
        return (
            <div id = 'navbar'>

                <div className='name-head'>
                    My Name
                </div>
            
            
                <div id = 'nav-links-container'>
                    
                    <Link to='/experiences'>
                        <div className = 'nav-links'>
                            Experiences
                        </div>
                    </Link>

                    <div className = 'nav-links'>
                        Projects
                    </div>

                    <div className = 'nav-links'>
                        Skills
                    </div>

                    <div className = 'nav-links'>
                        Resume
                    </div>

                </div>
                
            </div>
        );
    }
}

export default Navbar;

./components/experiences.jsx ./components/experiences.jsx

import React, { Component } from 'react';


class Experiences extends Component {
    
    render() { 
        return (
            <div>
                <h1>hi</h1>
            </div>
        );
    }
}
 
export default Experiences;

index.js索引.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import reportWebVitals from './reportWebVitals';
import Navbar from './components/Navbar';
import Home from './components/Home';
import Experiences from './components/experience';

import {
  BrowserRouter as Router, 
  Routes, 
  Route
} from 'react-router-dom';



ReactDOM.render(

  <React.StrictMode>

    <Navbar />

    <Router>

      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/experiences" element={<Experiences />} />
      </Routes>

    </Router>

  </React.StrictMode>,

  document.getElementById('root')
);


reportWebVitals();

The error doesn't come when I remove the <Link> from the experiences tag in navbar.当我从导航栏的体验标签中删除<Link>时,不会出现错误。 There is a similar question posted here: Error: useHref() may be used only in the context of a <Router> component but doesn't help.这里有一个类似的问题: Error: useHref() may be used only in the context of a <Router> component but doesn't help。

I'm using react router v6我正在使用反应路由器 v6

Issue问题

You are rendering the navbar outside the routing context.您在路由上下文之外呈现导航栏。 The Router isn't aware of what routes the links are attempting to link to that it is managing. Router不知道链接试图链接到它正在管理的路由。 The reason routing works when directly navigating to "/experiences" is because the Router is aware of the URL when the app mounts.直接导航到"/experiences"时路由起作用的原因是Router在应用程序挂载时知道 URL。

<Navbar /> // <-- outside router!!

<Router>
  <Routes>
    <Route path="/" element={<Home />} />
    <Route path="/experiences" element={<Experiences />} />
  </Routes>
</Router>

Solution解决方案

Move it inside the routing context so the Router is aware and can manage routing correctly.将其移动到路由上下文中,以便Router知道并正确管理路由。

<Router>
  <Navbar />
  <Routes>
    <Route path="/" element={<Home />} />
    <Route path="/experiences" element={<Experiences />} />
  </Routes>
</Router>

in React Route v6 you can solve this giving the route context to your entire App with < BrowserRouter >在 React Route v6 中,您可以使用 < BrowserRouter > 将路由上下文提供给整个应用程序来解决这个问题

This is an complete example of index.js这是 index.js 的完整示例

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import { App }  from './components/App/App.jsx';


ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>  //that is the key
      <App />
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById('root')
);

If you are still having problem with this one is because react-router-dom relies on React context to work when try unit testing it.如果您仍然对此有问题,是因为react-router-dom在尝试对其进行单元测试时依赖于 React 上下文来工作。 This makes <Link /> or <Route /> obsolete.这使得<Link /><Route />过时了。
Try reading the react-router-dom documentation .尝试阅读react-router-dom文档

Instead of using而不是使用

render(<Example />)

that have either or in it, you can try里面有或者里面的,你可以试试

render(<MemoryRouter>
    <Example />
</MemoryRouter>)

Hope this solve your problem希望这能解决你的问题

Links are inside Navbar & Navbar is outside of Router => links are outside of Router => Router will not manage Links链接导航栏内 & 导航栏在路由器之外=> 链接在路由器之外=> 路由器不会管理链接

Solution解决方案

Move the Navbar into Router section.将导航栏移动到路由器部分。 Example:例子:

<Router>
  <Navbar /> // <===========
  <Routes>
    <Route />
    <Route />
  </Routes>
</Router>

In react-router-dom:6.x and react:18.x , we should use in the following way to resolve the issuereact-router-dom:6.xreact:18.x中,我们应该使用以下方式来解决问题

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
import { App }  from './App.js';

const root = ReactDOM.createRoot(document.getElementById("root"));

root.render(
  <React.StrictMode>
    <Router>  // Router
      <App /> // Application
    </Router>
  </React.StrictMode>
); 

React Router v6 this problem common one, you can simply replace " index.js " code. React Router v6这个问题很常见,你可以简单地替换index.js代码。 you will got solution-你会得到解决方案-

import React from 'react';
import { createRoot } from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter } from 'react-router-dom';

const container = document.getElementById('root');
const root = createRoot(container);
root.render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>
);

Wrap navbar with BrowserRouter用 BrowserRouter 包裹导航栏

import { BrowserRouter, Routes, Route } from "react-router-dom";
<BrowserRouter>
    <AppNavBar />
    <Routes>
      <Route path="/" element={<Home />} />
      <Route path="/wall" element={<WallPost />} />
    </Routes>
  </BrowserRouter>

Install in your project React Router v6.在您的项目中安装React Router v6.

npm install react-router-dom@6 

Then use BrowserRouter in your index.js file, below like this:然后在index.js文件中使用BrowserRouter ,如下所示:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import { BrowserRouter } from 'react-router-dom';

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

root.render(
<React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>
);

This is very much an edge case, but in my case it turned out a lib I develop had react-router-dom: 6.0.2 installed and project that uses it v6.3.0这是一个非常边缘的情况,但在我的情况下,我开发的一个 lib 安装了react-router-dom: 6.0.2和使用它的项目v6.3.0

Your links just needs to be within a BrowserRouter component since you use v6 After importing您的链接只需要在 BrowserRouter 组件中,因为您使用 v6 导入后

<BrowserRouter>
    <Link to='page'>
</BrowserRouter>

This error happens because Link component needs to reach out to react-router context object. Your Navbar component is using Link component but Navbar is not wrapped by router context.发生此错误是因为Link组件需要到达react-router上下文 object。您的 Navbar 组件正在使用Link组件,但Navbar未被路由器上下文包裹。

A similar error happens in a testing environment.类似的错误发生在测试环境中。 If you have a component that uses Link component and if you render this component in a testing environment, you will get the same error because Link component needs to access a router context.如果您有一个使用Link组件的组件,并且如果您在测试环境中渲染该组件,您将收到相同的错误,因为Link组件需要访问路由器上下文。 In the case of test environment:以测试环境为例:

import { render } from "@testing-library/react";

// this will throw same error
test("testing", () => {
  render(<ComponentRendersLink/>); 
});

Solution in this case to wrap it with a router在这种情况下的解决方案是用路由器包裹它

// there are more router options
import { MemoryRouter } from "react-router-dom";

render(
    <MemoryRouter>
      <ComponentRendersLink />
    </MemoryRouter>
  );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 错误:useHref() 只能在 a 的上下文中使用<router>测试时的组件</router> - Error: useHref() may be used only in the context of a <Router> component when testing 错误:useHref() 只能在 a 的上下文中使用<Router>零件。 在注册中,js - Error: useHref() may be used only in the context of a <Router> component. in register,js 错误:useHref() 只能在 a 的上下文中使用<router>成分</router> - Error: useHref() may be used only in the context of a <Router> component 如何修复错误:useHref() 只能在 a 的上下文中使用<router>零件</router> - How to fix Error: useHref() may be used only in the context of a <Router> component 我如何解析“ useHref() 只能在上下文中使用<router>组件”当组件已经在里面时<router> ?</router></router> - How can I resolver " useHref() may be used only in the context of a <Router> component" when component is already inside <Router>? 未捕获的错误:useNavigate() 只能在<router>成分。 - 我做错了什么?</router> - Uncaught Error: useNavigate() may be used only in the context of a <Router> component. - What is it that I am doing wrong? 反应路由器错误“useRoutes()只能用于<router>成分。”</router> - React router error "useRoutes() may be used only in the contect of a <Router> component." 未捕获的错误:useLocation() 只能在 a 的上下文中使用<router>零件</router> - Uncaught Error: useLocation() may be used only in the context of a <Router> component 我不断收到“useNavigate() 只能在<router> component" 运行时出错,我不确定为什么</router> - I keep getting "useNavigate() may be used only in the context of a <Router> component" error when running this and I'm not sure why 错误:useLocation() 只能在 a 的上下文中使用<router>成分</router> - Error: useLocation() may be used only in the context of a <Router> component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM