代码之家  ›  专栏  ›  技术社区  ›  E_K

React中未定义操作负载

  •  0
  • E_K  · 技术社区  · 7 年前

    这是我收到的错误

    switch (action.type){
    case REGISTER_USER:
            console.log("Action ", action);// This prints {type: "REGISTER_USER", payload: undefined}
         return [action.payload.data, ...state];
        }
    return state;
    

    我认为这是因为 Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined} 是承诺的当前状态。 这是我的行动

    function registerUser(details, callback) {
    console.log(details);
    const request = axios.post(URL, {
        "email": details['email'],
        "name": details['username'],
        "password": details['password']
    }).then(() =>callback());
    console.log(request);
    return{
        type: REGISTER_USER,
        payload: request
       };
    }
    

    onFormSubmit(values){
        this.props.registerUser(values
            ,() =>{
            this.props.history.push("/login");
            }
        );
    }
    

    我的问题是,只有当承诺得到解决时,我如何才能回报行动?我是一个新手,在必要的时候纠正我。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Saltuk    7 年前

    您的操作无效。

    当您的操作包含异步过程时,您必须遵循以下逻辑

    function asyncStart(){
       return { type:'ASYNC_REQUEST' };
    }
    function asyncError(e){
     return {type:'ASYNC_ERROR', payload:{error:e}};
    }
    function asyncSuccess(res){
      return {type:'ASYNC_SUCCESS',payload:{result:res}};
    }
    function asyncMethod(){      
     return (dispatch, getState)=>{ 
         let state  = getState(); /// if you require state 
         dispatch(asyncStart());// or use  {type:'Something',payload:....};
          anAsyncSomething.then((val)=>{
              dispatch(asyncSuccess(val));  
           })
          .catch((e)=>{
              dispatch(asyncError(e));
         });
      }
    

    我希望这将有助于理解redux如何处理异步操作。