成功执行异步redux操作后显示通知

时间:2018-02-27 18:41:37

标签: reactjs redux redux-thunk

我试图找出在成功执行异步操作后显示sweetalert消息的最佳方法。所以我有一个ExcursionDetail组件,可以让你预订游览。这是简化的组件:

class ExcursionDetails extends Component {
    bookExcursion() {
        const userId = jwt_decode(localStorage.getItem('token')).sub;
        this
            .props
            .actions
            .bookExcursion(userId, this.props.match.params.id);
    }

    render() {
        ....
        <RaisedButton label="Book Excursion" onClick={e => this.bookExcursion()}/>
        ....
        )
    }
}

const mapStateToProps = (state, ownProps) => {
    return {excursion: state.excursion}
}

const mapDispatchToProps = (dispatch) => {
    return {
        actions: bindActionCreators(ExcursionActions, dispatch)
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(ExcursionDetails);

动作创建者:

export const bookExcursion = (userId, excursionId) => {
    return (dispatch, state) => {
        dispatch(requestBookExcursions())
        return ExcursionApi
            .bookExcursion(userId, excursionId)
            .then(resp => {
                if (resp.ok) {
                    return resp
                        .json()
                        .then(payload => {
                            dispatch(bookExcursionsSuccess(payload.data));
                        })
                }
            }).catch(err => {
                dispatch(bookExcursionsFailed(err));
            })
    }
}

然后显示甜蜜警报通知的最佳做法是什么?我想到的选项是:

  • 添加bookSuccess属性,我可以在ExcursionDetails组件中查看是真还是假,如果是,则调用sweetalert函数。

  • 创建特定于通知的操作和缩减器,并在我的组件中监听它。只有这个问题是我需要在每次通知调用后都有某种setTimeout来清除通知减少器,这看起来有点hacky。

  • 在我的reducer中调用甜蜜警报功能

  • 将回调传递给动作创建者

  • redux-thunk返回一个承诺;然而,即使http调用失败,它也会返回一个成功的承诺,所以这个选项似乎不可行。

2 个答案:

答案 0 :(得分:0)

我会使用你提到的第一个选项。 我创建了一个新组件并使用connect传递redux存储。我检查它是否在componentWillReceiveProps上为true并设置状态,然后你可以显示你的sweetalert。

答案 1 :(得分:0)

你可以在动作创建者中调用它。

您可以使用toastr之类的内容。

简单干净。

     export const bookExcursion = (userId, excursionId) => {
        return (dispatch, state) => {
            dispatch(requestBookExcursions())
            return ExcursionApi
                .bookExcursion(userId, excursionId)
                .then(resp => {
                    if (resp.ok) {
                        return resp
                            .json()
                            .then(payload => {
                                dispatch(bookExcursionsSuccess(payload.data));
                                //Here is your notification.
                                toastr.success('Have fun storming the castle!', 'Miracle Max Says')
                            })
                    }
                }).catch(err => {
                    dispatch(bookExcursionsFailed(err));
                })
        }
    }

相关问题