Javascript 在反应中使用 react-router 4 和 styled-component 时,不应在路由器外使用 Route 或 withRouter()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47314541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
You should not use Route or withRouter() outside a Router when using react-router 4 and styled-component in react
提问by JongHun Lee
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.
我正在尝试构建我的第一个投资组合网站,但在使用 react-router-dom 4.2.2 和 styled-components 2.2.3 的路由中陷入困境。
error message: You should not use Route or withRouter() outside a Router
错误消息:您不应在路由器外使用 Route 或 withRouter()
I also try using Link instead of NavLink but got error too(You should not use Link outside a Router)
我也尝试使用 Link 而不是 NavLink 但也出现错误(您不应该在路由器外使用 Link)
Someone help me please.
请有人帮助我。
navigationBar.js
导航栏.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
导航栏.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;
`;
回答by Bruce Seymour
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.
确保将主要的 react 渲染代码包装在路由器中。例如,使用 react-dom,您需要将应用程序包装在 Browser-Router 中。如果这是一个 Udacity 项目,这通常是 index.js 文件。
import { BrowserRouter } from 'react-router-dom';
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>
, document.getElementById('root'));
回答by Jo?o Cunha
Well you're using a NavLinkoutside of the BrowserRouter/HashRouter(whatever you're using)
那么您使用的是NavLink的外BrowserRouter/ HashRouter(你使用任何)
You said it yourself
你自己说的
You should not use Link outside a Router
你不应该在路由器外使用 Link
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
您必须始终在路由器内渲染它们
回答by Dinesh Khetarpal
I uninstalled @types/react-router-dom and installed it back. The error went away, don't know the magic but it worked for me.
我卸载了@types/react-router-dom 并重新安装了它。错误消失了,不知道魔法,但它对我有用。

