react router dom重定向没有重定向到我想要的组件,但它正在重定向到不同的路径



版本

"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-redux": "^7.2.0",
"react-router-dom": "^5.2.0",

我有一个问题,我的条件Redirect组件没有正常工作。是因为它在Switch组件之外吗。如果apiError为true,我希望它重定向到/error路由。由于我只测试了Error组件,而没有测试错误路由,因此条件有效。Redirect组件也可以工作,因为路径确实发生了更改,但组件没有被渲染。

render() {
const { currentUser, isLoaded, apiError } = this.state;
return ( 
<Router>
{currentUser ? (
<div className='App'>
<Switch>
<Route exact path='/title/:id' render={props => <ShowTitle {...props} /> } />
<Route exact path='/shuffle' render={props => <Titles {...props} isLoaded={isLoaded} /> } />
<Route exact path='/about' render={props => <About {...props} /> } />
<Route exact path='/all-titles' render={props => <Titles {...props} isLoaded={isLoaded} /> } />
<Route exact path='/error' render={props => <Error {...props} />} />
<Route exact path='/' render={props => <Redirect to={'/' + currentUser.viewType} /> } />
<Route exact path='/logout' component={Logout} />
<Redirect to='/all-titles' />
</Switch>
</div>
) : apiError ? <Redirect to='/error' /> : (
<Landing isLoaded={this.state.isLoaded}></Landing>
)}
</Router>
);

我看到一个逻辑错误。

<Route exact path='/error' render={props => <Error {...props} />} />

apiError时不存在。

这可能对你有用:

render() {
const { currentUser, isLoaded, apiError } = this.state;
let route = (<Landing isLoaded={isLoaded} />);
if (currentUser) {
route = (
<div className='App'>
<Switch>
<Route exact path='/title/:id' render={props => <ShowTitle {...props} /> } />
<Route exact path='/shuffle' render={props => <Titles {...props} isLoaded={isLoaded} /> } />
<Route exact path='/about' render={props => <About {...props} /> } />
<Route exact path='/all-titles' render={props => <Titles {...props} isLoaded={isLoaded} /> } />
<Route exact path='/error' render={props => <Error {...props} />} />
<Route exact path='/' render={props => <Redirect to={'/' + currentUser.viewType} /> } />
<Route exact path='/logout' component={Logout} />
<Redirect to='/all-titles' />
</Switch>
</div>
);
}
if (apiError) {
route = (
<Switch>
<Route exact path='/error' render={props => <Error {...props} />} />
</Switch>
);
}
return ( 
<Router>
{route}
</Router>
);
};

为了更好地使用,我建议您在HOC模块上静态声明所有路由,然后验证props并使用Redirect组件导航到其他路径。

最新更新