全新的react,尝试在“登录”页面上单击提交后重定向到“主页”。尝试按照react-router教程进行操作。
当我单击表单上的提交按钮并控制台记录状态和 fakeAuth.isAuthenticated 时,它们都返回 true。但是,重定向不会触发。
登录.js
class Login extends Component {
constructor(props) {
super(props);
this.state = {
portalId: "",
password: "",
redirectToReferrer: false
}
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
fakeAuth.authenticate(() => {
this.setState({
portalId: this.refs.portalId.value,
password: this.refs.password.value,
redirectToReferrer: true
})
})
e.preventDefault();
}
render() {
const redirectToReferrer = this.state.redirectToReferrer;
if (redirectToReferrer === true) {
<Redirect to="/home" />
}
路由.js
export const fakeAuth = {
isAuthenticated: false,
authenticate(cb) {
this.isAuthenticated = true
setTimeout(cb, 100)
},
signout(cb) {
this.isAuthenticated = false
setTimeout(cb, 100)
}
}
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={() => (
fakeAuth.isAuthenticated === true
? <Component {...this.props}/>
: <Redirect to="/" />
)}/>
)
export default () => (
<BrowserRouter>
<div>
<Navbar />
<Switch>
<Route path="/" exact component={Login} />
<Route path="/register" exact component={Register} />
<Route path="/home" exact component={Home} />
</Switch>
</div>
</BrowserRouter>
);