这是App.jsx中配置的最外层路由
<div className="App">
<HashRouter>
<Switch>
<Route exact path="/" component={() => (
<Redirect to={`/home/index`}/>
)} />
<Route path="/home" component={Home} />
<Route path="/login" component={Login} />
<Route path="/account" component={Account} />
</Switch>
</HashRouter>
</div>
在/home 这个组件下有三个嵌套的子路由
<div className="home">
<h1>Home组件</h1>
<Switch>
<Route path="/home/index" component={HomeIndex} />
<Route path="/home/order" component={HomeOrder} />
<Route path="/home/assets" component={Assets} />
</Switch>
</div>
现在我通过this.props.history.push('/home/index')这样跳转/home/index /home/order /home/assets 页面能够正常渲染组件
但是我如果访问this.props.history.push('/home') 这样,子组件不会渲染出来
我想到了通过重定向去跳转/home/index,但是不知道应该怎么写,像App.jsx那样Redirect没用,甚至导致/home/index /home/order /home/assets 访问都不渲染了
我设置Redirect 重定向到/home/index 在控制台报错,Home组件不显示子组件
Warning: You tried to redirect to the same route you're currently on: "/home/index"
<div className="home">
<Switch>
<Redirect to={`/home/index`}/>
<Route path="/home/index" component={HomeIndex} />
<Route path="/home/order" component={HomeOrder} />
<Route path="/home/assets" component={Assets} />
</Switch>
</div>
然后我在Home.jsx的componentWillMount钩子中去强制跳转/home/index
componentWillMount() {
this.props.history.push('/home/index')
}
虽然能实现访问/home跳转到/home/index,但是我认为这样不是正确的处理方式
所以想问问,在react-router中嵌套路由,如何在路由不匹配的情况下,显示默认子组件
<Redirect to="/home/index" from="/home" exact />