在反应中使用 react-router 4 和 styled-component 时,不应在路由器外使用 Route 或 withRouter() [英] You should not use Route or withRouter() outside a Router when using react-router 4 and styled-component in react

查看:14
本文介绍了在反应中使用 react-router 4 和 styled-component 时,不应在路由器外使用 Route 或 withRouter()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建我的第一个投资组合网站,但在使用 react-router-dom 4.2.2 和 styled-components 2.2.3 的路由方面陷入了困境.

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.

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

我也尝试使用 Link 而不是 NavLink,但也出现错误(您不应在路由器外使用 Link)

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

请有人帮助我.

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;
`;

推荐答案

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

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'));

这篇关于在反应中使用 react-router 4 和 styled-component 时,不应在路由器外使用 Route 或 withRouter()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆