嘿,我正尝试使用<Redirect/>
中的react-router
将用户成功登录到首页。但是直到现在都没有成功。超时有效,但它使我进入空白页而不是Home.js
。您知道如何解决此问题吗?
Confirm.js
import React, { Component } from 'react';
import { BrowserRouter as Router } from 'react-router-dom'
import { Redirect } from 'react-router'
import Route from 'react-router-dom/Route';
import Home from './HomePage'
class Confirm extends Component {
state = {
redirect: false
}
componentDidMount() {
this.id = setTimeout(() => this.setState({ redirect: true }), 3000)
}
componentWillUnmount() {
clearTimeout(this.id)
}
render() {
// setTimeout(function(){alert('Hello!');},3000);
return (
<Router>
<div className='Confirm'>
<Route path='/confirm' render={
() => {
return this.state.redirect
? <Redirect exact to="/" component={Home} />
: <div className='Success'>
<h1>Confirmed Session</h1>
<p>Okay you are good to go . Your session has started .</p>
</div>
}
} />
</div>
</Router>
);
}
}
export default Confirm;
答案 0 :(得分:1)
您的<Route />
必须彼此毗邻居住:
root.js
<Router>
<Switch>
<Route path="/" component={Home} />
<Route path="/confirm" component={Confirm} />
</Switch>
</Router>
confirm.js
if (this.state.redirect) {
return <Redirect to="/" >
} else {
<div>
your confirm page
</div>
}
现在您可以从一个重定向到另一个,并且应该替换整个页面。
还可以查看react-router库中的<Switch>
组件。