码迷,mamicode.com
首页 > 其他好文 > 详细

[XState] Track Infinite States with with XState Context

时间:2020-01-20 00:06:35      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:ide   lease   pre   color   inter   imp   text   please   number   

Consider a text input. It would be impossible for anyone to model every value you could possibly put into it, because the number of possible values is infinite. This is an infinite state.

Infinite state can be tracked and utilized by XState machines as "extended state". This extended state is called context. Context is passed to every function that is triggered by the machine: actions, activities, guards, and more.

In this lesson we learn how to set context and update it through assign actions.

 

const { Machine, interpret, assign } = require("xstate");

const inputMachine = Machine(
  {
    id: "inputMachine",
    initial: "input",
    context: {
      value: "Please enter a color"
    },
    states: {
      input: {
        on: {
          CHANGE_VALUE: {
            actions: ["changeInput"]
          }
        }
      }
    }
  },
  {
    actions: {
      changeInput: assign((context, event) => {
        return { value: event.color };
      })
    }
  }
);

const service = interpret(inputMachine)
  .onTransition(state => {
    console.log(state.context); // red
  })
  .start();
service.send({ type: "CHANGE_VALUE", color: "red" });

 

[XState] Track Infinite States with with XState Context

标签:ide   lease   pre   color   inter   imp   text   please   number   

原文地址:https://www.cnblogs.com/Answer1215/p/12215812.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!