在使用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
问题描述
我正在尝试构建我的第一个投资组合网站,并使用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但也遇到错误(你不应该使用路由器外的链接)
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-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屋!