如果用户在 React 上转到非 public url,我该如何重定向?
How do I redirect if user goes to a non public url on React?
好的,所以我有一个名为 Page 的模板组件。如果我去不同的路线,相同的模板将用于不同的信息。这是我在页面中的内容:
class Page extends Component {
render() {
console.log(this.props.children);
return (
<div className="page">
<Header></Header>
{this.props.children}
</div>
);
}
}
这是 Routes.js 组件:
<Route path="/" render={() => (
<Page>
<Switch>
<Route path='/home' component={Home}></Route>
<Route path='/users/new' component={RegistrationForm}></Route>
<Route path='/users' component={Table}></Route>
</Switch>
</Page>
)}></Route>
但是,当我转到 localhost:3000/ 时,它显示的模板没有任何内容。如果用户转到 /.
,我想重定向到 /home
我试过放置
<Redirect>
像这样:
<Route path='/' render={() => (
<Fragment>
<Redirect to='/home'></Redirect>
<Page>
<Switch>
<Route path='/home' component={Home}></Route>
<Route path='/users/new' component={RegistrationForm}></Route>
<Route path='/users' component={Table}></Route>
</Switch>
</Page>
</Fragment>
)}></Route>
现在我访问的每个页面都会重定向到 /home。有谁知道如何进行这项工作?
应该很简单:)
您只需将 from prop 添加到您的 <Redirect>
并将其作为第一条路线:
<Redirect from="/" to="/home" />
您需要使用 from
和 exact
属性。为了同时使用这两个属性,Redirect
必须是 Switch
组件的子组件(查看文档 here):
<Route path='/' render={() => (
<Page>
<Switch>
<Redirect exact from='/' to='/home'></Redirect>
<Route path='/home' component={Home}></Route>
<Route path='/users/new' component={RegistrationForm}></Route>
<Route path='/users' component={Table}></Route>
</Switch>
</Page>
)}></Route>
好的,所以我有一个名为 Page 的模板组件。如果我去不同的路线,相同的模板将用于不同的信息。这是我在页面中的内容:
class Page extends Component {
render() {
console.log(this.props.children);
return (
<div className="page">
<Header></Header>
{this.props.children}
</div>
);
}
}
这是 Routes.js 组件:
<Route path="/" render={() => (
<Page>
<Switch>
<Route path='/home' component={Home}></Route>
<Route path='/users/new' component={RegistrationForm}></Route>
<Route path='/users' component={Table}></Route>
</Switch>
</Page>
)}></Route>
但是,当我转到 localhost:3000/ 时,它显示的模板没有任何内容。如果用户转到 /.
,我想重定向到 /home我试过放置
<Redirect>
像这样:
<Route path='/' render={() => (
<Fragment>
<Redirect to='/home'></Redirect>
<Page>
<Switch>
<Route path='/home' component={Home}></Route>
<Route path='/users/new' component={RegistrationForm}></Route>
<Route path='/users' component={Table}></Route>
</Switch>
</Page>
</Fragment>
)}></Route>
现在我访问的每个页面都会重定向到 /home。有谁知道如何进行这项工作?
应该很简单:)
您只需将 from prop 添加到您的 <Redirect>
并将其作为第一条路线:
<Redirect from="/" to="/home" />
您需要使用 from
和 exact
属性。为了同时使用这两个属性,Redirect
必须是 Switch
组件的子组件(查看文档 here):
<Route path='/' render={() => (
<Page>
<Switch>
<Redirect exact from='/' to='/home'></Redirect>
<Route path='/home' component={Home}></Route>
<Route path='/users/new' component={RegistrationForm}></Route>
<Route path='/users' component={Table}></Route>
</Switch>
</Page>
)}></Route>