使用通过操作传递的参数填充Redux Reducer

时间:2019-07-29 18:41:39

标签: reactjs redux react-redux

我目前正在尝试通过操作将动态ID传递到我的redux reducer中。我可以将此ID一直拉到我的操作中,但是我在最后一步上很挣扎,这是将值添加到我的redux存储中。

这是我到目前为止的代码,非常感谢您的帮助!

组件: 这会将我的docDeleteId传递到我的modalDocDeleteAction

<Icon iconType="delete" onClick={() => modalDocDeleteAction(document.documentId)}/>

const mapDispatchToProps = dispatch => ({
    modalDocDeleteAction: docDeleteId =>
        dispatch(modalDocDeleteAction(docDeleteId))
});

export default connect(
    null,
    mapDispatchToProps
)(Results);

操作: 由于ThunkreduxMulti中间件而造成的分派性

export function modalDocDeleteAction(docDeleteId) {
    console.log(docDeleteId); // ID is retrieved successfully
    return dispatch => {
        dispatch([{ type: MODAL_DOC_DELETE }, modalOpenAction()]);
    };
}

异径管:

case "MODAL_DOC_DELETE":
        return {
            ...state,
            modalTitle: "Delete Document?",
            modalText:
                    "Deleting a document will permanently remove it from S3",
            closeText: "No, Keep Document",
            continueText: "Yes, Delete Document",
            docDeleteId: !!!ID GOES HERE!!!
        };

我希望通过操作传递docDeleteId参数来填充我的减速器。我正努力在网上找到任何可以做到这一点的东西,但是我需要在其他地方可以使用的ID,所以我真的希望是这样!

任何对此的帮助将是巨大的!非常感谢!

1 个答案:

答案 0 :(得分:3)

我们通常要做的是将有效负载关键字中的自定义数据传递给减速器。像这样编辑代码

export function modalDocDeleteAction(docDeleteId) {
    console.log(docDeleteId); // ID is retrieved successfully
    return dispatch => {
        dispatch([{ type: MODAL_DOC_DELETE, payload: docDeleteID }, modalOpenAction()]);
    };
}

,然后在减速器中按如下方式访问它

case "MODAL_DOC_DELETE":
        return {
            ...state,
            modalTitle: "Delete Document?",
            modalText:
                    "Deleting a document will permanently remove it from S3",
            closeText: "No, Keep Document",
            continueText: "Yes, Delete Document",
            docDeleteId: action.payload
        };