繁体   English   中英

React Redux Thunk 回调到另一个函数——TypeError: 无法读取未定义的属性“then”

[英]React Redux Thunk with callback to another function -- TypeError: Cannot read property 'then' of undefined

我正在使用react+redux。 我有一个包含数据和图像的模态表单,成功后我需要关闭从 redux 返回的模态 else 显示错误。 在调度函数中,我还有 1 个回调函数来将图像存储到 S3。 我正在从 redux-thunk 返回承诺,但我不断收到“TypeError:无法读取未定义的属性‘then’”。

成分

handleSubmit = e => {
        e.preventDefault();

        if(this.isFieldEmpty()){
            this.setState({ message: "All fields are mandatory with at least 1 pic" });
            return;
        } else {
            this.setState({ message: "" });
        }

        const data = {
            name: this.state.name,
            description : this.state.description,
            points : this.state.points,
            attributes : this.state.attributes,
            images : this.state.images,
            created_by: localStorage.getItem('id'),
        }
        this.props.createItem(data).then(() => {
            this.hideModal();
        })
    }

const mapDispatchToProps = dispatch => {
    return {
        createItem: data => {
            return dispatch(createItem(data))
        },
    };
};

行动

const saveItemImages = (images,successcb, failurecb) => {
    if(images.length > 0){
        const formData = new FormData();
        for(var x = 0; x<images.length; x++) {
            formData.append('image', images[x])
        }
        const token = localStorage.getItem('token');
        fetch(`${backendUrl}/upload/item-images/`, {
            method: "POST",
            headers: {
                'Authorization': `Bearer ${token}`
            },
            credentials: 'include',
            body: formData
        })
        .then(res => {
            if(res.status === 200){
                res.json().then(resData => {
                    successcb(resData.imagesUrl);
                });
            }else{
                res.json().then(resData => {
                    failurecb(resData.message);
                }) 
            }
        })
        .catch(err => {
            console.log(err);
        });
    } else {
        successcb([]);
    }
}

export const createItem = data =>  { return (dispatch) => {
    saveItemImages(data.images, imagesUrl => {
        data.images = imagesUrl;
        return fetch(`${backendUrl}/admin/createItem`, {
            method: 'POST',
            headers: {
                'Accept': 'application/json,  text/plain, */*',
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${data.token}`
                },
            credentials: 'include',
            body: JSON.stringify(data)
        })
        .then(res => {
            if(res.status === 200){
                res.json().then(resData => {
                    dispatch({
                        type: ADMIN_CREATE_ITEM_SUCCESS,
                        payload: resData
                    })
                    return true;
                });
            }else{
                console.log("Save failed");
                res.json().then(resData => {
                    dispatch({
                        type: ADMIN_CREATE_ITEM_FAILED,
                        payload: {
                            message: resData.message
                        }
                    })
                }) 
            }
        })
        .catch(err => {
            dispatch({
                type: ADMIN_CREATE_ITEM_FAILED,
                payload: {
                    message: `Internal Error -- ${err}`
                }
            })
        });

    }, failedMessage => {
        let payload = {responseMessage: failedMessage}
            dispatch({
                type: ADMIN_CREATE_ITEM_FAILED,
                payload: payload
            })
    });
};
};

在此先感谢您的帮助

您应该返回一个Promise来为这样的操作创建异步流:

export const createItem = data => dispatch => new Promise((resolve, reject) => {

  // do something was a success
  resolve();

  // do something was a fail
  reject();

});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM