You should not use <Link> outside a

2020-01-27 04:04发布

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

You should not use <Link> outside a <Router>

My app is set up like so:

Parent component

const router = (
  <div className="sans-serif">
    <Router histpry={browserHistory}>
      <Route path="/" component={Main}>
        <IndexRoute component={PhotoGrid}></IndexRoute>
        <Route path="/view/:postId" component={Single}></Route>
      </Route>
    </Router>
  </div>
);

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

Child/Main component

export default () => (
  <div>
    <h1>
      <Link to="/">Redux example</Link>
    </h1>
  </div>
)

Any idea what I'm doing wrong here?

Here's a Sandbox link to demonstrate the problem.

9条回答
Summer. ? 凉城
2楼-- · 2020-01-27 04:32

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

查看更多
The star\"
3楼-- · 2020-01-27 04:33

For JEST users

if you use Jest for testing and this error happen just wrap your component with <BrowserRouter>

describe('Test suits for MyComponentWithLink', () => {
it('should match with snapshot', () => {
const tree = renderer
  .create(
    <BrowserRouter>
      <MyComponentWithLink/>
    </BrowserRouter>
  )
  .toJSON();
 expect(tree).toMatchSnapshot();
 });
});
查看更多
▲ chillily
4楼-- · 2020-01-27 04:33

Enclose Link component inside BrowserRouter component

 export default () => (
  <div>
   <h1>
      <BrowserRouter>
        <Link to="/">Redux example</Link>
      </BrowserRouter>
    </h1>
  </div>
)
查看更多
登录 后发表回答