How to compose redux reducers with dependent state

后端 未结 4 1806
别跟我提以往
别跟我提以往 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:36

    This is a good use case for Reselect:

    Create a selector to access your state and return derived data.

    As an example:

    import { createSelector } from 'reselect'
    
    const widgetsSelector = state => state.widgets;
    const selectedWidgetsSelector = state => state.selection.widgets;
    
    function minCoordinateSelector(widgets, selected) {
      const x_list = selected.map((widget) => {
        return widgets[widget].x;
      });
    
      const y_list = selected.map((widget) => {
        return widgets[widget].y;
      });
    
      return {
        x: Math.min(...x_list),
        y: Math.min(...y_list)
      };
    }
    
    const coordinateSelector = createSelector(
      widgetsSelector,
      selectedWidgetsSelector,
      (widgets, selected) => {
        return minCoordinateSelector(widgets, selected);
      }
    );
    

    The coordinateSelector now provides access to your min x and y properties. The above selector will only be updated when either the widgetsSelector or selectedWidgetsSelector state changes, making this a very performant way to access the properties you are after and avoids duplication in your state tree.

提交回复
热议问题