gpt4 book ai didi

javascript - 如何在授权成功后立即重定向到首页?

转载 作者:行者123 更新时间:2023-11-30 14:09:32 24 4
gpt4 key购买 nike

为了在成功登录后访问主页,用户需要刷新整个页面(否则他不会被自动重定向到主页)。可能的问题是什么以及如何解决?这是我的源代码:

App.js

class App extends Component {
render() {
return (
<BrowserRouter>
<Switch>
<Route path='/' exact component={ MainPage }></Route>
<Route path='/login' component={ LogIn }></Route>
<Route component={ NotFoundPage }></Route>
</Switch>
</BrowserRouter>
);
}
}

export default App;

登录.js

const userIdRegex = RegExp(
/^[uU]*1+[0-9]*$/
);

class LogIn extends Component {

constructor(props) {
super(props);

this.state = {
userId: null,
password: null,
fullName: undefined,
responseError: false,
loggedIn: false,
formErrors: {
userId: "",
password: ""
}
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}

handleChange = e => {
e.preventDefault();
const { name, value } = e.target;
let formErrors = { ...this.state.formErrors };

switch (name){

case "userId":
formErrors.userId = userIdRegex.test(value)
? ""
: "Invalid user ID";
break;
case "password":
formErrors.password =
value.length < 8 ? "Invalid password" : "";
break;
default:
break;
}

this.setState({ formErrors, [name]: value }, () => console.log(this.state));
};

handleSubmit = e => {
e.preventDefault();

axios.post('url', { userId: e.target.elements.userId.value,
password: e.target.elements.password.value })
.then((response) => {
if(response.status=200){
this.setState({ loggedIn: true });
let responseJSON = response;
sessionStorage.setItem("userData", responseJSON);
} else {
console.log("Log In Error");
}
}).catch((error) => {
console.log(error);
this.setState({ responseError: true });
});

};

render() {
if ( this.state.loggedIn ) {
return (<Redirect to={'/'} />);
}
if ( sessionStorage.getItem('userData') ){
return (<Redirect to={'/'} />);
}
const { formErrors } = this.state;
const responseError = this.state.responseError;
// const loggedIn = this.state.loggedIn;
// const { from } = this.props.location.state || '/';

return (
<div className="wrapper">
<div className="form-wrapper">
<img src={Logo} className="App-logo" alt="Logo" />
<p>To Log In enter your user ID and password.</p>
<form onSubmit={this.handleSubmit} noValidate>
<div className="userId">
<input
autoFocus
className={formErrors.userId.length > 0 ? "error" : null}
placeholder="User ID"
type="text"
name="userId"
noValidate
defaultValue="u"
onChange={this.handleChange}
/>
{formErrors.userId.length > 0 && (
<span className="errorMessage">{formErrors.userId}</span>
)}
</div>
<div className="password">
<input
className={formErrors.password.length > 0 ? "error" : null}
placeholder="Password"
type="password"
name="password"
noValidate
onChange={this.handleChange}
/>
{formErrors.password.length > 0 && (
<span className="errorMessage">{formErrors.password}</span>
)}
</div>
<div className="createAccount">
<button type="submit" disabled={!this.state.userId} disabled={!this.state.password}>
Log in
</button>
</div>
</form>
{ responseError==true && (
<span className="response-error errorMessage">Please enter valid user values</span>
) }
</div>
</div>
)}
}

export default LogIn;

主页.js

class MainPage extends Component {

constructor(props) {
super(props);
this.state = {
redirect: false,
}
this.logout = this.logout.bind(this);
this.componentDidMount = this.componentDidMount.bind(this);
}

componentDidMount() {
if( sessionStorage.getItem('userData') ){
console.log('User Logged In');
} else {
this.setState({redirect: true})
}
}

logout(){
sessionStorage.setItem('userData', '');
sessionStorage.clear();
this.setState({redirect: true})
}
render(){
if (this.state.redirect) {
return (<Redirect to={'/login'} />);
}
return(
<div>
<p>Welcome</p>
<button onClick={this.logout}>Logout</button>
</div>

);
}
}
export default MainPage;

当我从 MainPage.js 中删除 componentDidMount() 方法时,它解决了重定向问题,但无需通过 URL 登录即可访问主页。

最佳答案

所有路由组件都可以访问 props 中的 history 对象,所以你可以在成功登录后执行 this.props.history.push('/') LogIn 组件。

class LogIn extends Component {
// ...

handleSubmit = e => {
e.preventDefault();

axios
.post("url", {
userId: e.target.elements.userId.value,
password: e.target.elements.password.value
})
.then(response => {
if (response.status === 200) {
this.setState({ loggedIn: true });
sessionStorage.setItem("userData", response);
this.props.history.push("/");
} else {
console.log("Log In Error");
}
})
.catch(error => {
console.log(error);
this.setState({ responseError: true });
});
};

// ...
}

关于javascript - 如何在授权成功后立即重定向到首页?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54733795/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com