你不应该在 Piral 的 <Router> 之外使用 <Link>

You should not use <Link> outside a <Router> in Piral

我在默认 Piral 实例中调试 pilet 时遇到此错误:

Uncaught Error: Invariant failed: You should not use <Link> outside a <Router>

奇怪的是下一个日志条目报告错误来自 inside a Router:

react_devtools_backend.js:2430 The above error occurred in the <Context.Consumer> component:
    in Link
    in Unknown
    in Suspense (created by ErrorBoundary)
    in ErrorBoundary
    in Unknown (created by Menu)
    in li (created by MenuItem)
    in MenuItem
    in Unknown (created by Menu)
    in ul (created by MenuContainer)
    in div (created by MenuContainer)
    in div (created by MenuContainer)
    in nav (created by MenuContainer)
    in header (created by MenuContainer)
    in MenuContainer
    in Unknown (created by Menu)
    in Menu (created by Layout)
    in div (created by Layout)
    in Layout
    in Unknown (created by PiralContent)
    in PiralContent (created by PiralView)
    in Router (created by BrowserRouter)
    in BrowserRouter
    in Unknown (created by PiralView)
    in PiralProvider (created by PiralView)
    in PiralView (created by Piral)
    in Piral

我的绒毛index.jsx:

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

const App = () => 'My pilet'

export function setup(app) {
  app.registerPage('/my-pilet', App)
  app.registerMenu(() => <Link to="/my-pilet">My Pilet</Link>)
}

我的 Piral 实例使用 piral-cli 提供的样板,完全没有改变。它甚至有一个默认菜单项,可以正常工作而不会出现错误:

(“未找到”是 Piral 提供的默认菜单项)

为什么会出现此错误?

错误是不言自明的,您只需将 包含在 Router 标签中。试试这个:

import { BrowserRouter as Router, Link } from 'react-router-dom'

const App = () => 'My pilet'

export function setup(app) {
  app.registerPage('/my-pilet', App)
  app.registerMenu(() => <Router> <Link to="/my-pilet">My Pilet</Link> <Router>)
}

来源:https://reactrouter.com/web/example/url-params

你的设置一定有问题。如果出现此错误,则表示您的 Link 与应用 shell 中的路由上下文不同。我怀疑你不分享 react-router-dom。把它放在你的 pilet package.json 的 peerDependencies 中。