You should not use <Link> outside a

后端 未结 10 1597
既然无缘
既然无缘 2020-11-27 15:55

I\'m trying to set up react-router in an example application, and I\'m getting the following error:

You should not use  outside a 
         


        
相关标签:
10条回答
  • 2020-11-27 16:14

    I kinda come up with this code :

    import React from 'react';
    import { render } from 'react-dom';
    
    // import componentns
    import Main from './components/Main';
    import PhotoGrid from './components/PhotoGrid';
    import Single from './components/Single';
    
    // import react router
    import { Router, Route, IndexRoute, BrowserRouter, browserHistory} from 'react-router-dom'
    
    class MainComponent extends React.Component {
      render() {
        return (
          <div>
            <BrowserRouter history={browserHistory}>
              <Route path="/" component={Main} >
                <IndexRoute component={PhotoGrid}></IndexRoute>
                <Route path="/view/:postId" component={Single}></Route>
              </Route>
            </BrowserRouter>
          </div>
        );
      }
    }
    
    render(<MainComponent />, document.getElementById('root'));
    

    I think the error was because you were rendering the Main component, and the Main component didn't know anything about Router, so you have to render its father component.

    0 讨论(0)
  • 2020-11-27 16:14

    If you don't want to change much, use below code inside onClick()method.

    this.props.history.push('/');
    
    0 讨论(0)
  • 2020-11-27 16:17

    Write router in place of Main in render (last line in the code). Like this ReactDOM.render(router, document.getElementById('root'));

    0 讨论(0)
  • 2020-11-27 16:19

    You can put the Link component inside the Router componet. Something like this:

     <Router>
            <Route path='/complete-profiles' component={Profiles} />
            <Link to='/complete-profiles'>
              <div>Completed Profiles</div>
            </Link>
          </Router>
    
    0 讨论(0)
提交回复
热议问题