【问题标题】:Error when put <BrowserRouter> and useRoutes(routes) in A function component in React将 <BrowserRouter> 和 useRoutes(routes) 放入 React 中的功能组件时出错
【发布时间】:2022-07-08 05:16:58
【问题描述】:

我在我的反应应用程序中使用react-router-dom。 当我使用时:

function App() {
    return (
        <BrowserRouter>{ useRoutes(routes) }</BrowserRouter>
    );
}

我收到错误消息:Uncaught Error: useRoutes() may be used only in the context of a &lt;Router&gt; component.

我已经搜索了如何修复它并将我的代码结构更改为:

function App() {
    return (
        <BrowserRouter><Foo/></BrowserRouter>
    );
}
function Foo() { 
    return useRoutes(routes)
}

代码运行正常。

作为初学者,我无法说出上面两个 sn-p 之间的确切区别,有人可以帮忙吗?

【问题讨论】:

    标签: javascript reactjs react-router jsx


    【解决方案1】:
    Uncaught Error: useRoutes() may be used only in the context of a <Router> component.
    

    这条消息的全部意思是,ReactTree 中需要有一个比 App 组件更高的路由上下文提供程序,该组件在使用 useRoutes 钩子时尝试使用它。

    一个更清楚的坏例子:

    function App() {
      const routes = useRoutes(routes); // <-- (2) but needed here!
      return (
        <BrowserRouter> // <-- (1) context provided here
          {routes}
        </BrowserRouter>
      );
    }
    

    在这里您可以清楚地看到路由器低于App 组件并且没有提供给App 的路由上下文。

    这就是第二个 sn-p 起作用的原因,它提供的路由上下文比使用它的组件更高。

    function App() {
      return (
        <BrowserRouter> // <-- (1) context provided here
          <Foo/> // <-- (2) context consumed here
        </BrowserRouter>
      );
    }
    
    function Foo() { 
      return useRoutes(routes);
    }
    

    【讨论】:

      【解决方案2】:

      这是另一个引发错误的示例,感谢@drew-reese 的解释,该示例已得到修复:

      create-react-app 构建以下 TypeScript 测试文件:

      import React from 'react';
      import { render, screen } from '@testing-library/react';
      import App from './App';
      
      test('renders learn react link', () => {
        render(<App />);
        const linkElement = screen.getByText(/learn react/i);
        expect(linkElement).toBeInTheDocument();
      });
      

      解决方法是包含 BrowserRouter

      import { BrowserRouter } from "react-router-dom";
      

      并包装&lt;App /&gt; 以获取路由上下文:

      render(<BrowserRouter><App /></BrowserRouter>);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-02
        • 1970-01-01
        • 2022-01-22
        • 1970-01-01
        • 2020-05-30
        相关资源
        最近更新 更多