Invariant failed: You should not use outside a

后端 未结 20 1258
伪装坚强ぢ
伪装坚强ぢ 2020-12-03 20:55

I use react-router-dom for routing in my React application. Part of my app extracted in another package. List of dependencies looks like this:

相关标签:
20条回答
  • 2020-12-03 20:59

    I had the same problem with my Create React App when running tests and I solved it by placing <Router></Router inside App.js instead of in Index.js as I have always done.

    Before:

    Index.js

    ReactDOM.render(
        <React.StrictMode>
            <GlobalStyle />
            <Router>
                <App />
            </Router>
        </React.StrictMode>,
    document.getElementById('root')
    );
    

    App.js

    return (
        <div className="App">
            <Header />
            <Route path="/blabla" component={Whatever}
        </div>
    )
    

    After:

    Index.js:

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

    App.js:

    return (
        <div className="App">
            <Router>
                <Header />
                <Route path="/blabla" component={Whatever}
            </Router>
        </div>
    )
    
    0 讨论(0)
  • 2020-12-03 20:59

    I have solved this issue by importing

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

    and wrapped all the Route components under the Router component

     <Router>
         <Route exact path='/' component={HomePage} />
     </Router>
    
    0 讨论(0)
  • 2020-12-03 20:59

    just change "react-router" on "react-router-dom"

    import {Route} from "react-router";
    

    to

    import {Route} from "react-router-dom";
    
    0 讨论(0)
  • 2020-12-03 21:04

    I fixed that problem just importing the "BrowserRouter" from 'react-router-dom' in index.js(on create-react-app) then you can use:

        <BrowserRouter>
           <App>
         </BrowserRouter>
    

    replacing where were:

        ReactDOM.render(
          <React.StrictMode>
            <App />
          </React.StrictMode>,
         document.getElementById('root'));
    
    0 讨论(0)
  • 2020-12-03 21:04

    Using the <Link> tag in a component that doesn't have the imported could give this error, try importing the BrowserRouter from 'react-router-dom'

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

    then make sure to wrap your linked tags in the tag

    0 讨论(0)
  • 2020-12-03 21:04

    You have a hanging comma at the end of the render call after document.getElementById('root').

    render(
      <BrowserRouter>
        <App />
      </BrowserRouter>,
      document.getElementById('root'),
    );
    
    0 讨论(0)
提交回复
热议问题