How to compose redux reducers with dependent state

后端 未结 4 1839
别跟我提以往
别跟我提以往 2021-02-04 08:47

I am working on a React/Redux application that allows for \"widgets\" to be added to a page and manipulated in 2D space. It is a requirement that multiple widgets can be selecte

4条回答
  •  心在旅途
    2021-02-04 09:51

    If you use the thunk middleware (https://github.com/gaearon/redux-thunk) you can make the SET_SELECTION action a thunk, which will allow it to read entire state before making the dispatch that will be received by your reducer.

    // action creator
    function setSelection(selectedWidgetId) {
        return (dispatch, getState) => {
            const {widgets} = this.getState();
            const coordinates = getSelectionCoordinates(widgets, selectedWidgetIds);
    
            dispatch({
                type: SET_SELECTION,
                payload: {
                    widgets: selectedWidgets,
                    x: coordinates.x,
                    y: coordinates.y
                }
            });
    }
    

    This way you get all the information you need in your selection reducer without having to pass along the list of all widget-objects to your action.

提交回复
热议问题