首页 > 解决方案 > 不变量失败:您不应该使用外面

问题描述

我正在尝试创建 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>
        )
    }
}

有人能告诉我我的代码有什么问题吗

标签: reactjstypescriptreact-routerreact-router-dom

解决方案


您忘记添加路由器组件。

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

const rootElement = document.getElementById("root");
render(<BrowserRouter><App /></BrowserRouter>, rootElement);

- 编辑

你不能使用Link没有指定的组件Router你可以使用BrowserRouter(它使用内部历史 API)、HashRouter(url 哈希)或通用Router(你必须为其提供一些配置)


推荐阅读