0

我有很多这样的代码:

export const getNodeShapeSize = ({
  scaleToFit,
  compress,
  expanded
}: {
  scaleToFit: boolean;
  compress: boolean;
  expanded: boolean;
}): number => {
  if (scaleToFit) {
    return ShapeSizes.full;
  }

  if (compress && !expanded) {
    return ShapeSizes.preview;
  }

  return ShapeSizes.expanded;
};

我想知道是否可以使用 xstate 来清理它?我可以有 3 个状态

scaleToFit
compressed
expnded

到目前为止,我有这个:

export const treeMachineConfig = Machine({
  strict: true,
  id: 'treefsm',
  initial: TreeSFMActionTypes.Unkonwn,
  states: {
    unknown: {
      on: {
        scaleToFit: 'scaledToFit',
        compress: 'compressed',
        expand: 'expanded'
      }
    },
    scaledToFit: {
      on: {
        compress: 'compressed',
        expand: 'expanded'
      }
    },
    compressed: {
      on: {
        scaleToFit: 'scaledToFit',
        expand: 'expanded'
      }
    },
    expanded: {
      on: {
        scaleToFit: 'scaledToFit',
        compress: 'compressed'
      }
    }
  }
});

但是价值在哪里呢?我会把它们放在上下文中吗?

4

1 回答 1

1

是的,您可以将它们放入context( docs ) 中,它看起来像这样:

import { Machine, assign } from 'xstate';

export const treeMachineConfig = Machine({
  strict: true,
  id: 'treefsm',
  context: {
    width: 0,
    height: 0
  },
  initial: TreeSFMActionTypes.Unkonwn,
  states: {
    // ...
    compressed: {
      // Just an example: set to this size whenever 'compressed' state is entered
      entry: assign({ x: 10, y: 10 }),
      on: // ...
    },
    expanded: {
      entry: assign({ /* ... */ }),
      on: // ...
    }
  }
});
于 2019-06-10T10:51:40.053 回答