【问题标题】:Action payload is undefined in React动作负载在 React 中未定义
【发布时间】:2017-11-11 09:09:55
【问题描述】:

这是我收到的错误无法读取未定义的属性“数据”

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");
        }
    );
}

我的问题是如何仅在 Promise 解决后才返回操作?我是初学者,在必要时做出反应纠正我。

【问题讨论】:

标签: javascript reactjs promise react-redux


【解决方案1】:

您的操作无效。

虽然您的操作包含异步过程,但您必须遵循此逻辑

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 如何处理异步操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 2018-04-14
    • 1970-01-01
    • 1970-01-01
    • 2019-01-23
    • 2016-07-08
    相关资源
    最近更新 更多