我可以在 xstate 的不同状态下有不同的值吗

can I have different values in different states in xstate

我有很多这样的代码:

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'
      }
    }
  }
});

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

是的,您可以将它们放在 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: // ...
    }
  }
});