我正在使用react建立一个在线数据库,并且已经设置了路由,如果用户未经过身份验证,他们将被重定向到登录页面。
但是,我遇到了嵌套路线的困难。我认为实施的某些部分是不正确的。
2个问题:
exact
<Route/>
道具
exact
道具,则在FixedDrawer组件中找到的<Links/>
将无效。点击它们中的任何一个将指向&#34; 404&#34;页。 我在这里做错了什么?
为了简单起见,我将只分享组件的渲染部分。
代码如下:
App.js(PageShell仅用于动画页面过渡)
import LoginPage from "./pages/LoginPage";
import Dashboard from "./pages/Dashboard";
import NotFound from "./pages/NotFound";
.
.
.
render() {
const childProps = {
isAuthenticated: this.state.isAuthenticated,
userHasAuthenticated: this.userHasAuthenticated
};
return (
<div className="App">
<Switch>
<Route path="/login" exact component={PageShell(LoginPage)} />
<Route path="/" exact component={PageShell(Dashboard)} />
<Route component={NotFound} />
</Switch>
</div>
);
Dashboard.js
render() {
return (
<div>
<NavBar user={this.state.user} />
<FixedDrawer handleSetCategory={this.handleSetCategory} />
<Switch>
<Route path="/athletes" render={() => <AthletesDataTable />} />
<Route path="/races" render={() => <RacesDataTable />} />
</Switch>
</div>
);
}
FixedDrawer.js
class FixedDrawer extends Component {
constructor() {
super();
this.state = {};
}
render() {
return (
<Drawer variant="permanent" elevation={10}>
<List component="nav" style={{ top: 65 }}>
<ListItem button>
<ListItemIcon>
<FaceIcon />
</ListItemIcon>
<Link to="/athletes" style={{ textDecoration: "none" }}>
<ListItemText primary="Athletes" />
</Link>
</ListItem>
<ListItem button>
<ListItemIcon>
<GroupIcon />
</ListItemIcon>
<Link to="/teams" style={{ textDecoration: "none" }}>
<ListItemText primary="Teams" />
</Link>
</ListItem>
<ListItem button>
<ListItemIcon>
<DateRangeIcon />
</ListItemIcon>
<Link to="/meets" style={{ textDecoration: "none" }}>
<ListItemText primary="Meets" />
</Link>
</ListItem>
<ListItem button>
<ListItemIcon>
<PoolIcon />
</ListItemIcon>
<Link to="/races" style={{ textDecoration: "none" }}>
<ListItemText primary="Races" />
</Link>
</ListItem>
<ListItem button>
<ListItemIcon>
<AssignmentIcon />
</ListItemIcon>
<Link to="/results" style={{ textDecoration: "none" }}>
<ListItemText primary="Race Results" />
</Link>
</ListItem>
</List>
</Drawer>
);
}
}
答案 0 :(得分:1)
&#34; LINK&#34;组件将尝试匹配确切的路由。因为,&#34; /遇见&#34;,&#34; / teams&#34;与您提供的路线不匹配,它将给出404页。
return (
<div className="App">
<Navbar />
<Sidebar />
<Switch>
<Route path="/login" exact component={PageShell(LoginPage)} />
<Route path="/:val" component={PageShell(SomePage)} />
<Route path="/" exact component={PageShell(Dashboard)} />
<Route component={NotFound} />
</Switch>
<Footer />
</div>
);
我建议您按上述方式编写路线组件。并且在&#34; SomePage&#34;的componentDidMount中;组件,你可以得到&#34; val&#34;正如上面路径中提到的那样,#。; this.props.match&#34;对象并渲染&#34; SomePage&#34;组件根据您想要的路线。
Ex:在SomePage的didMount函数中:
componentDidMount(){
this.setState({val: this.props.match.params.val})
}
render(){
return(
<div>
{
this.state.val === 'teams' ? <TeamsComponent /> : null
}
{
this.state.val === 'meets' ? <MeetsComponent /> : null
}
</div>
)
}