我想在我的react应用程序中添加私有路由,当用户登录名将重定向到帐户页面时,我使用firebase作为数据库。
我看了一些教程,但是我认为代码是针对像这样的mern堆栈的。您能帮助我如何实现私有路由,这是我的代码。
注册
class SignUp extends React.Component {
constructor() {
super();
this.state = {
displayName: "",
email: "",
password: "",
confirmPassword: "",
};
}
handleSubmit = async (event) => {
event.preventDefault();
const { displayName, email, password, confirmPassword } = this.state;
if (password !== confirmPassword) {
alert("Password don't match");
return;
}
try {
const { user } = await auth.createUserWithEmailAndPassword(
email,
password
);
await createUserProfileDocument(user, { displayName });
this.setState({
displayName: "",
email: "",
password: "",
confirmPassword: "",
});
} catch (error) {
console.error(error);
}
};
handleChange = (event) => {
const { name, value } = event.target;
this.setState({ [name]: value });
};
render() {
const { displayName, email, password, confirmPassword } = this.state;
return (
<div className="sign-up">
{Form}
</div>
);
}
}
export default SignUp;
登录
class SignIn extends React.Component {
constructor(props) {
super(props);
this.state = {
email: "",
password: "",
};
}
handleSubmit = async (event) => {
event.preventDefault();
const { email, password } = this.state
try {
await auth.signInWithEmailAndPassword(email, password)
this.setState({ email: "", password: "" });
} catch (error) {
console.log(error);
}
};
handleChange = (event) => {
const { value, name } = event.target;
this.setState({ [name]: value });
};
render() {
return (
<div className="sign-in">
{form}
</div>
);
}
}
export default SignIn;
应用js
class App extends React.Component {
constructor() {
super();
this.state = {
currentUser: null,
};
}
unsubscribeFromAuth = null;
componentDidMount() {
this.unsubscribeFromAuth =
auth.onAuthStateChanged(async (userAuth) => {
if (userAuth) {
const userRef = await createUserProfileDocument(userAuth);
userRef.onSnapshot((snapShot) => {
this.setState({
currentUser: {
id: snapShot.id,
...snapShot.data(),
},
});
});
} else {
this.setState({currentUser: userAuth})
}
});
}
componentWillUnmount() {
this.unsubscribeFromAuth();
}
render() {
return (
<div>
<Header currentUser={this.state.currentUser} />
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/shop" component={ShopPAge} />
<Route path="/signin" component={SignInAndSignUpPage} />
</Switch>
</div>
);
}
}
export default App;
答案 0 :(得分:0)
您有两个选择
首先,在用this.props.history.push
包装组件之后,组件本身使用withRouter
import { withRouter } from 'react-router-dom'
...
try {
await auth.signInWithEmailAndPassword(email, password)
this.setState({ email: "", password: "" });
this.props.history.push('/shop') // in case you want redirect to shop
}
...
export default withRouter(SignIn);
第二,在路由声明中使用render
代替component
,并使用Redirect
组件
import { Redirect } from 'react-router-dom'
...
<Route path="/signin" render={()=>this.state.currentUser ? <Redirect to='/shop' /> :<SignInAndSignUpPage/>} />