You should not use Route or withRouter() outside a Router when using react-router 4 and styled-component in react

折月煮酒 提交于 2019-12-21 06:47:06

问题


I'm trying to build my first portfolio website and got stuck in routing using react-router-dom 4.2.2 and styled-components 2.2.3.

error message: You should not use Route or withRouter() outside a Router

I also try using Link instead of NavLink but got error too(You should not use Link outside a Router)

Someone help me please.

navigationBar.js

import React, { Component } from 'react';
import { NavigationContainer, NavItem } from './navigationBar.style';

class NavigationBar extends Component {
  render() {
    return (
      <NavigationContainer>
        <NavItem to="/">Home</NavItem>
        <NavItem to="/projects">Project</NavItem>
      </NavigationContainer>
    );
  }
}

export default NavigationBar;

navigationBar.style.js

import styled from 'styled-components';
import { Flex, Div } from 'theme/grid';
import { NavLink } from 'react-router-dom';

export const NavigationContainer = styled(Flex)`
  position: fixed;
  right: 20px;
  top: 0.5em;
  font-size: 1em;  
`;
export const NavItem = styled(NavLink)`
  position: relative;
  padding-left: 10px;
  cursor: pointer;
`;

回答1:


Make sure you wrap the main react render code in the Router. For example, with react-dom you need to wrap the app in Browser-Router. If this is a Udacity project, this is typically the index.js file.

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

ReactDOM.render(
   <BrowserRouter>
     <App />
   </BrowserRouter>

  , document.getElementById('root'));



回答2:


Well you're using a NavLink outside of the BrowserRouter/HashRouter (whatever you're using)

You said it yourself

You should not use Link outside a Router

Make sure that you have the structure like this

// App render or whatever
render() {
  return (
    <BrowserRouter>
       <NavigationBar />
       {`whatever else you doin'`}
    </BrowserRouter>
  );
}

You must always render them inside a Router



来源:https://stackoverflow.com/questions/47314541/you-should-not-use-route-or-withrouter-outside-a-router-when-using-react-route

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!