reactjs - 不变量失败:您不应该使用外面
问题描述
我正在尝试创建 reactjs 组件并在另一个 tsx 文件中使用,但出现以下错误 Invariant failed: You should not use outside
我的代码如下,我的代码框https://codesandbox.io/s/zen-sound-ztbjl
class Sidebar extends Component<ISidebarProps & RouteComponentProps<{}>> {
constructor(props: ISidebarProps & RouteComponentProps<{}>) {
super(props)
this.state = {}
}
componentDidMount = (): void => {
this.initMenu()
}
componentDidUpdate = (prevProps: any): void => {
if (this.props.type !== prevProps.type) {
this.initMenu()
}
}
initMenu = (): void => {
const mm = new MetisMenu('#side-menu')
let matchingMenuItem = null
const ul = document.getElementById('side-menu')
const items = ul.getElementsByTagName('a')
for (let i = 0; i < items.length; ++i) {
if (this.props.location.pathname === items[i].pathname) {
matchingMenuItem = items[i]
break
}
}
if (matchingMenuItem) {
this.activateParentDropdown(matchingMenuItem)
}
}
activateParentDropdown = (item: any) => {
item.classList.add('active')
const parent = item.parentElement
if (parent) {
parent.classList.add('mm-active')
const parent2 = parent.parentElement
if (parent2) {
parent2.classList.add('mm-show')
const parent3 = parent2.parentElement
if (parent3) {
parent3.classList.add('mm-active') // li
parent3.childNodes[0].classList.add('mm-active') // a
const parent4 = parent3.parentElement
if (parent4) {
parent4.classList.add('mm-active')
}
}
}
return false
}
return false
}
render() {
return (
<React.Fragment>
<div className='vertical-menu'>
<div data-simplebar className='h-100'>
{this.props.type !== 'condensed' ? (
// <Scrollbars style={{ maxHeight: '100%' }}>
<SidebarContent />
) : (
// </Scrollbars>
<SidebarContent />
)}
</div>
</div>
</React.Fragment>
)
}
}
有人能告诉我我的代码有什么问题吗
解决方案
您忘记添加路由器组件。
import { BrowserRouter } from "react-router-dom";
const rootElement = document.getElementById("root");
render(<BrowserRouter><App /></BrowserRouter>, rootElement);
- 编辑
你不能使用Link
没有指定的组件Router
你可以使用BrowserRouter
(它使用内部历史 API)、HashRouter
(url 哈希)或通用Router
(你必须为其提供一些配置)
推荐阅读
- android - Django Channels 和 Django Rest Framework 集成
- python - 使用 python gnupg 解密
- .htaccess - 将旧 IDX 主页列表页面重定向到搜索页面
- c++ - SDL - 如何在不停止代码执行的情况下在 C++ 中异步播放音频?
- c++ - Visual Studio 2017 中的 Google 测试问题
- android - 无法连接到 BLE 设备
- javascript - SignalR dotnet core MVC 单元测试
- sql - 将 Select(多个结果)的结果存储在变量中(稍后在 in 语句中使用)
- c++ - 在 Windows 中删除文件时,CMD 和 PowerShell 有什么区别?
- c++ - 如何在运行时定期触发函数