Javascript React组件和分派操作的异步问题
我正在创建一个React Redux应用程序,它使用一个用express.js构建的API 我有一个登录表单,当用户尝试使用错误的凭据登录时,我想向用户显示一条消息。我曾尝试以多种方式构建这种行为。在这里,我有一个非常合乎逻辑和完全同步的方法 我设置了一个登录组件,从其道具的userActions调用函数。组件通过Javascript React组件和分派操作的异步问题,javascript,reactjs,redux,redux-thunk,Javascript,Reactjs,Redux,Redux Thunk,我正在创建一个React Redux应用程序,它使用一个用express.js构建的API 我有一个登录表单,当用户尝试使用错误的凭据登录时,我想向用户显示一条消息。我曾尝试以多种方式构建这种行为。在这里,我有一个非常合乎逻辑和完全同步的方法 我设置了一个登录组件,从其道具的userActions调用函数。组件通过导出默认连接(null,{login,register})(login)连接 现在让我们看一下登录。我将把注册代码留在那里,因为我不知道这是否/如何影响我的登录功能。我的问题是,我可以
导出默认连接(null,{login,register})(login)连接代码>
现在让我们看一下登录。我将把注册代码留在那里,因为我不知道这是否/如何影响我的登录功能。我的问题是,我可以获得创建的通知以及预期的登录和验证,但我无法获得“身份验证”状态,这是决定重定向所必需的
我必须处理两种情况:
登录成功=>重定向到“/”显示欢迎消息李>
登录失败=>在同一页面上显示错误消息
我可以获得创建的通知以及预期的登录和验证,但是我无法获得“auth”状态,这是决定重定向所必需的
有人能帮我吗?谢谢大家!
onSubmit方法@login.js:
onSubmit=async e=>{
e、 预防默认值();
const{name,email,password}=this.state;
//检查错误
{....}
//注册或登录并通知用户
设auth=false;
if(此.state.register){
this.props.register({name,email,password})
.then((res)=>{auth=res.success;console.log(`register then:${res}`);})
}否则{
this.props.login({email:email,password:password})
.then((res)=>{auth=res.success;console.log(`login then:${res}`);})
}
if(auth){this.props.history.push('/')}
}
登录方法@userActions.js:
export const login=authData=>async dispatch=>{
post('/api/v1/users/login',authData)
。然后(res=>{
开始阶段(res);
派遣({
类型:登录,
有效载荷:res.data.user
});
通知用户('login',dispatch,res);
返回{success:true}
})
.catch(错误=>{
返回{success:false}
});
};
以下是API调用响应之前加载的组件
在渲染休息之前进行检查
//create a use state variable for validation return a response
constructor(props) {
super(props);
this.state = {
login:'' }
};
// any method here
onSubmit = async e => {
e.preventDefault();
}
/* api call*/
{
this.setState({
login: json.error.message
});
// other code
}
render() {
if (!this.state.user ) {
return null;
}
return (
<>
//componest wait still not get repose
<p>{this.state.login} <p>
<>
}
....
//创建用于验证的use state变量并返回响应
建造师(道具){
超级(道具);
此.state={
登录名:'}
};
//这里有什么办法吗
onSubmit=async e=>{
e、 预防默认值();
}
/*api调用*/
{
这是我的国家({
登录名:json.error.message
});
//其他代码
}
render(){
如果(!this.state.user){
返回null;
}
返回(
//平静的等待还是得不到休息
{this.state.login}
}
....
我设法创建了我想要的体验,使用componentDidUpdate检查state.user,它通过登录更新
componentDidUpdate = () => {
if (Object.keys(this.props.user).length !== 0) { this.props.history.push('/') }
}
...
const mapStateToProps = state => ({
user: state.user
})
export default connect(mapStateToProps, { login, register })(Login);
我不明白你的答案。为什么onSubmit中有构造函数?我建议你检查一下如何使用React钩子开发相同的功能。它使倾听更改和管理组件的状态变得更容易。我自己也遇到过类似的挑战,在我看来,钩子是一个巨大的改进。