我在带有导航栏和内容的页面上使用react-router。
const App = () => (
<Router>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/shape/:activeTab" component={Shapes} />
<Redirect from="/shape" to="/shape/triangle" />
</Switch>
</Router>
);
- 形状
class Shapes extends React.Component {
getActiveTab() {
switch (this.props.match.params.activeTab) {
case 'triangle':
return Triangle;
case 'circle':
return Circle;
case 'square':
return Square;
default:
return Triangle;
}
}
render() {
return (
<div className="wrapper">
// this is where the navbar renders.
<ul>
<li>
<NavLink exact to={`/shape/triangle`}> Triangle </NavLink>
</li>,
<li>
<NavLink exact to={`/shape/circle`}> Circle </NavLink>
</li>,
<li>
<NavLink exact to={`/shape/square`}> Square </NavLink>
</li>,
</ul>
// this is where the content renders.
<div className="content">
{
this.getActiveTab().data.map(tuple =>
<div>
{tuple.description}
</div>,
)
}
</div>
</div>
);
}
};
现在,当我点击localhost:8080/shape
时,我会通过导航重定向到正确的页面
导航也正常工作(我点击Triangle会将我重定向到localhost:8080/shape/triangle
)
但是,当我尝试直接访问页面localhost:8080/shape/triangle
时,我得到了404!
仅在我首先访问/shapes
页面然后使用导航时才有效。
我需要在此处解决以确保我可以路由到shape/*
页。
注意:我指的是https://reacttraining.com/react-router/web/api/Switch