【问题标题】:Unhandled Rejection (Error): Actions must be plain objects. Use custom middleware for async actions. React + Redux [duplicate]未处理的拒绝(错误):操作必须是普通对象。使用自定义中间件进行异步操作。 React + Redux [重复]
【发布时间】:2023-03-22 17:27:02
【问题描述】:

//REDUX

export const clinicAdd = async (name, address, semester, pay) => (
    (dispatch) => { dispatch({ type: CLINIC_ADD});
         axios.post('myURL', 
         { name, address, semester, pay} ,config)
             .then( data => clinicAddSuccess(dispatch, data))
             .catch( () => clinicAddFail(dispatch));
    }
);

const clinicAddSuccess = async( dispatch , data) => {
    console.log("Success");
        dispatch({
            type: CLINIC_ADD_SUCCESS,
            payload: data,
            
        })
};
 
const clinicAddFail = async (dispatch) => {
    console.log("Fail");
    dispatch({
        type: CLINIC_ADD_FAIL
    })
};







//using 

   onPress = async(e) => {
        e.preventDefault();   
        const {name,address,payment,semester, error} = this.props;
        await this.props.clinicAdd(name,address,semester,payment);
        this.secondFun()
    };
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

我正在尝试解决此问题。我是新手。 我希望在 OnPress 函数执行时等待 ClinicAdd 结束,然后执行 secondFunction

我在我的 redux 商店中使用 applyMiddleware(thunk)

【问题讨论】:

标签: javascript reactjs asynchronous react-redux


【解决方案1】:

你的动作函数是错误的。应该是:

const clinicAdd = (name, address, semester, pay) => async dispatch => {
  await axios
    .post('myURL', { name, address, semester, pay }, config)
    .then(data => clinicAddSuccess(data))
    .catch(() => clinicAddFail());

  dispatch({ type: CLINIC_ADD });
};

const clinicAddSuccess = data => ({
    type: CLINIC_ADD_SUCCESS,
    payload: data, 
});

const clinicAddFail = () => ({
    type: CLINIC_ADD_FAIL
});

【讨论】:

  • 你能指出有什么区别吗?我找到了它,但与原版相比需要一段时间。解释原因可能会有所帮助
  • 区别在于dispatch应该是异步函数,而不是自定义参数
  • 我试过了,结果还是一样
  • secondFun 一直执行到 this.props.clinicAdd 结束
  • same :(( 其他函数有什么问题吗?
猜你喜欢
  • 1970-01-01
  • 2021-11-02
  • 2021-11-04
  • 2020-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-30
  • 2020-11-05
相关资源
最近更新 更多