Redux动作必须是普通对象错误

时间:2020-04-11 15:21:13

标签: reactjs api redux

我正在使用ReactJS开发前端应用程序。我以前没有使用过redux,但出现错误。 我有以下代码:

import { connect } from 'react-redux';
import PharmacistPreregisterComponent from "../components/PharmacistPreregisterComponent";
import { postPreregisteredPharmacist } from "../actions";

const mapDispatchToProps = dispatch => ({
    onClick: (email, drugstoreId, alert) => {
        dispatch(
            postPreregisteredPharmacist(email, drugstoreId, alert)
        );
    }
});

export default connect (
    null,
    mapDispatchToProps
)(PharmacistPreregisterComponent)

在PharmacistPreregisterComponent中,方法:

handleSubmit(event) {
        event.preventDefault();

        this.onClick(
            this.state.email,
            this.state.drugstoreId,
            this.state.alertMessage);
        this.setState({
            email: '',
            drugstoreId: '',
            alertMessage: ''
        });
    }

以及以下操作:

const PREREGISTER_PHARMACIST_SAVE_URL = "http://localhost:3000/admin/preregister/add"
export function postPreregisteredPharmacist(email, drugstoreId, alert) {
    return dispatch => {
        console.log("in action");
        return fetch(PREREGISTER_PHARMACIST_SAVE_URL, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ "email": email, "drugstoreId": drugstoreId})
        }).then ( response => {
            console.log(response);
        }).catch( error => {
            console.log(error);
        })
    }
}

提交表单时,我得到Actions must be plain objects. Use custom middleware for async actions.,但似乎无法弄清问题所在。

1 个答案:

答案 0 :(得分:0)

正如您在评论中所建议的那样,由于您不希望基于API请求来更新redux状态,因此您可以简单地将函数转换为常规函数,而不是操作

还考虑仅在API请求成功时将状态设置为空

import PharmacistPreregisterComponent from "../components/PharmacistPreregisterComponent";
import { postPreregisteredPharmacist } from "../actions";

handleSubmit(event) {
        event.preventDefault();

        postPreregisteredPharmacist (
            this.state.email,
            this.state.drugstoreId,
            this.state.alertMessage
        ).then((response) => {
          console.log(response);
          this.setState({
            email: '',
            drugstoreId: '',
            alertMessage: ''
        });
      });

    }

export default PharmacistPreregisterComponent)

const PREREGISTER_PHARMACIST_SAVE_URL = "http://localhost:3000/admin/preregister/add"
export function postPreregisteredPharmacist(email, drugstoreId, alert) {
    return fetch(PREREGISTER_PHARMACIST_SAVE_URL, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ "email": email, "drugstoreId": drugstoreId})
        })
}
相关问题