在使用react-router 4和styled-component进行响应时,不应在路由器外使用Route或withRouter()

问题描述 投票:27回答:2

我正在尝试构建我的第一个投资组合网站,并使用react-router-dom 4.2.2和styled-components 2.2.3陷入路由。

错误消息:您不应在路由器外使用Route或withRouter()

我也尝试使用Link而不是NavLink,但也有错误(你不应该使用路由器外的链接)

请有人帮帮我。

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;
`;
javascript reactjs react-router styled-components
2个回答
31
投票

确保将主反应渲染代码包装在路由器中。例如,使用react-dom,您需要将应用程序包装在Browser-Router中。如果这是一个Udacity项目,这通常是index.js文件。

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

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

  , document.getElementById('root'));

10
投票

那么你在BrowserRouter / HashRouter之外使用NavLink(无论你使用什么)

你自己说的

您不应该使用路由器外的链接

确保你有这样的结构

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

您必须始终在路由器中呈现它们

© www.soinside.com 2019 - 2024. All rights reserved.