【问题标题】:Configuring react-router-dom generates an error: Invariant failed: You should not use <Link> outside a <Router>配置 react-router-dom 会产生错误:Invariant failed: You should not use <Link> outside a <Router>
【发布时间】:2020-02-20 05:41:37
【问题描述】:

我正在尝试设置一个新的 react 应用程序。

我在配置路由器时遇到问题(我认为)。

到目前为止,我的 index.js 有:

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

import './index.css';
import App from './App';
import About from './pages/about/About';

import * as serviceWorker from './serviceWorker';

ReactDOM.render(<App />, document.getElementById('root'));

ReactDOM.render(
    <Router>
      <div>
        <Switch>
            <Route path="/" exact component={App} />
            <Route path="/about" component={About} />

        </Switch>
      </div>  
    </Router>,
    document.getElementById('root')
);

我的 / 路径中还有一个页脚,其中包含以下链接:

import React from 'react';
import { Link } from 'react-router-dom'
import { Row, Col, Typography } from 'antd';


const { Text, Title } = Typography;

function StandardFooter() {
    return (
      <div>
        <Row type="flex" justify="space-around">
            <Col span={4}>
                <Text type="secondary">
                    <Link to={'/about'} >About</Link>
                </Text> <br />

            </Col>
            <Col span={4}>
                <Text strong>Legal</Text>
            </Col>

        </Row>
      </div>
    );
  }

  export default StandardFooter;

但是当我尝试渲染它时,我收到一条错误消息:错误:不变量失败:您不应该在路由器之外使用链接

我已尝试删除并重新安装 react-router-dom。它没有任何区别。是不是少了一个步骤?

【问题讨论】:

    标签: reactjs react-router-dom


    【解决方案1】:

    删除此行:ReactDOM.render(&lt;App /&gt;, document.getElementById('root'));

    这一行很可能是错误的根源,因为您的 &lt;App /&gt; 组件树包含一个 &lt;Link /&gt;,并且在这种情况下您正在渲染它而没有 &lt;BrowserRouter /&gt;

    【讨论】:

    • 有时候我就是这样的驴。我忘了删除启动代码。谢谢。我必须等待 6 分钟才能接受
    猜你喜欢
    • 2020-05-02
    • 1970-01-01
    • 2021-01-28
    • 2023-01-31
    • 2020-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-25
    相关资源
    最近更新 更多