简体   繁体   English

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

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

I am using react+redux.我正在使用react+redux。 I have a modal form with data and images and on success I need to close the modal else display error returned from redux.我有一个包含数据和图像的模态表单,成功后我需要关闭从 redux 返回的模态 else 显示错误。 In the dispatch function I have 1 more callback function to store images to S3.在调度函数中,我还有 1 个回调函数来将图像存储到 S3。 I am returning promise from the redux-thunk but I keep getting "TypeError: Cannot read property 'then' of undefined".我正在从 redux-thunk 返回承诺,但我不断收到“TypeError:无法读取未定义的属性‘then’”。

Component成分

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

Action行动

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

Thanks in advance for any help在此先感谢您的帮助

You should return a Promise to create async flow for the action like this:您应该返回一个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.

相关问题 Redux Thunk函数后的回调:未捕获的TypeError:无法读取未定义的属性&#39;then&#39; - Callback after Redux Thunk function: Uncaught TypeError: Cannot read property 'then' of undefined 如何使用 Redux 在 Redux 中调度异步操作 Thunk:TypeError:无法读取未定义的属性“加载” - How to dispatch async action in Redux using Redux Thunk: TypeError: Cannot read property 'loading' of undefined 类型错误:无法在反应/redux 测试中读取未定义的属性“路径名” - TypeError: Cannot read property 'pathname' of undefined in react/redux testing 错误:类型错误:无法读取 React-Redux 中未定义的属性“map” - Error: TypeError: Cannot read property 'map' of undefined in React-Redux TypeError:无法读取未定义的属性“操作”(React-Redux) - TypeError: Cannot read property 'actions' of undefined (React-Redux) React Redux - TypeError:无法读取未定义的属性“道具” - React Redux - TypeError: Cannot read property 'props' of undefined TypeError:无法读取未定义的属性“ 0”。 React Redux应用 - TypeError: Cannot read property '0' of undefined. React Redux App Redux和React。 未捕获的TypeError:无法读取未定义的属性“ dispatch” - Redux and React. Uncaught TypeError: Cannot read property 'dispatch' of undefined 反应来自 Redux 的工作。 TypeError:无法读取未定义的属性“类型” - React work from Redux . TypeError: Cannot read property 'type' of undefined 反应 - Redux | 未处理的拒绝(类型错误):无法读取未定义的属性“数据” - React - Redux | Unhandled Rejection (TypeError): Cannot read property 'data' of undefined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM