【问题标题】:Redux updating state too slow after axios.post callaxios.post 调用后 Redux 更新状态太慢
【发布时间】:2021-09-16 09:28:22
【问题描述】:

所以我正在尝试使用 react、redux 应用一个简单的登录功能。 通过使用 axios post 请求发送到 django 服务器(用户名、密码) 但问题出在调用它的组件上。 例如组件 A。 所以场景是这样的:

  1. 用户输入用户名和密码并点击提交
  2. handle submit 触发调用 onAuth(authLogin) 的操作方法
  3. authLogin 更新状态是否成功
  • 问题是状态被更新为慢并且 state.error 没有价值 这让我在用户没有输入有效用户名时将用户重定向到某个地方,通过 如何等待 axios 调用完成并等待状态更新?

    class A extends Component{
      handleSubmit = (values) => {
          this.props.onAuth(values.username, values.password);
          if(!this.props.error){
             // redirecting somewherr
          }else{
             // giving error message
          }
      }
    
     render() {
      return{
          <Form onSubmit={this.handleSubmit}>
           <Input name="username"/>
          <Input name="password"/>
         </Form>
      }
    
    }
      const mapStateToProps = (state) => {
       return {
         error: state.error,
       };
    };
    
       const mapDispatchToProps = (dispatch) => {
        return {
               onAuth: (username, password) => 
      dispatch(actions.authLogin(username,password)),
        };
    };
    

    导出默认连接(mapStateToProps, mapDispatchToProps)(LoginView);

}

  • 我的初始状态

    常量初始状态 = { 令牌:空, 错误:空, 加载:假, };

  • 登录操作

      export const authLogin = (username, password) => {
        return (dispatch) => {
          dispatch(authStart());
        axios
        .post("http://127.0.0.1:8000/login/", {
          username: username,
          password: password,
        })
        .then((res) => {
          // some more code here
          dispatch(authSuccess(token));
        })
        .catch((err) => {
          dispatch(authFail(err));
        });
    };
    

    };

  • authFail 操作

    export const authFail = (error) => {
     return {
       type: actionTypes.AUTH_FAIL,
       error: error,
    

    } ; };

【问题讨论】:

    标签: reactjs redux react-redux


    【解决方案1】:

    认为解决这个问题的方法是使用重定向函数的 setTimeout 函数

    setTimeout(() => {
        // redirecting function call
       }, 3000);
    

    这已经帮我解决了

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-11
      • 2018-07-21
      • 1970-01-01
      • 2019-12-04
      • 2017-03-22
      • 1970-01-01
      • 2021-08-29
      • 1970-01-01
      相关资源
      最近更新 更多