简体   繁体   English

有没有办法在useEffect的反应组件中设置xstate机的state?

[英]Is there a way to set the state of an xstate machine in a react component in useEffect?

I have the following React.js component that needs the following:我有以下需要以下 React.js 组件:

  • Persist the state when a button is clicked through using fetch to call a server side API.当通过使用 fetch 调用服务器端 API 单击按钮时,坚持 state。
  • When the component is initialized that the state is set in the component after calling useEffect that uses fetch to call a server side API to get the current state of the object. When the component is initialized that the state is set in the component after calling useEffect that uses fetch to call a server side API to get the current state of the object.

Here is the display of the component这是组件的显示


状态按钮


Here is what I have so far.这是我到目前为止所拥有的。

import React, { useEffect, useState } from 'react';
import { useParams, useHistory } from "react-router-dom";
import { createMachine } from 'xstate';
import { useMachine } from "@xstate/react";
import {MagellanButton} from "./Styles";
import 'bootstrap/dist/css/bootstrap.min.css';
import '../App.css';

const approvalMachine = createMachine({
    id: 'approve',
    initial: 'Not Submitted',
    context: {
        retries: 0
    },
    states: {
        'Not Submitted': {
            on: {
                SUBMIT: 'Pending Approval'
            }
        },
        'Pending Approval': {
            on: {
                CANCEL: 'Not Submitted',
                CHANGE: 'Change Request',
                DENIED: 'Denied',
                APPROVED: 'Approved'
            }
        },
        'Change Request': {
            on: {
                RESUBMITTED: 'Pending Approval',
                CANCEL: 'Not Submitted'
            }
        },
        Denied: {
            type: 'final'
        },
        Approved: {
            on: {
                PUBLISH: 'Published'
            }
        },
        Published: {
            type: "final"
        }
    }
});

function MagellanStateManager({id}) {
    const parameters = useParams();
    const history = useHistory()
    const [state, send] = useMachine(approvalMachine);

    useEffect(() => {
    }, []);

    return (
        <span style={{float: "right", marginTop: 8}}>
            <span className="m-form-label  ml-3">State:</span> <span>{state.value}</span>
            <MagellanButton className="ml-3" disabled={!state.nextEvents.includes('SUBMIT')} onClick={() => send('SUBMIT')}>Submit</MagellanButton>
            <MagellanButton className="ml-3" disabled={!state.nextEvents.includes('CANCEL')} onClick={() => send('CANCEL')}>Cancel</MagellanButton>
            <MagellanButton className="ml-3" disabled={!state.nextEvents.includes('CHANGE')} onClick={() => send('CHANGE')}>Change</MagellanButton>
            <MagellanButton className="ml-3" disabled={!state.nextEvents.includes('RESUBMITTED')} onClick={() => send('RESUBMITTED')}>Resubmit</MagellanButton>
            <MagellanButton className="ml-3" disabled={!state.nextEvents.includes('DENIED')} onClick={() => send('DENIED')}>Deny</MagellanButton>
            <MagellanButton className="ml-3" disabled={!state.nextEvents.includes('APPROVED')} onClick={() => send('APPROVED')}>Approve</MagellanButton>
            <MagellanButton className="ml-3" disabled={!state.nextEvents.includes('PUBLISH')} onClick={() => send('PUBLISH')}>Publish</MagellanButton>
        </span>
    )

}

export default MagellanStateManager;

From the comment from Taxel, I was able to find my solution.从 Taxel 的评论中,我找到了我的解决方案。 Here is the changed react element.这是更改后的反应元素。 I would appreciate any additional comments to make this even better.我将不胜感激任何其他评论,以使其变得更好。

Thank You!谢谢你!

import React, {useEffect, useState} from 'react';
import { createMachine, interpret } from 'xstate';
import {MagellanButton} from "./Styles";
import 'bootstrap/dist/css/bootstrap.min.css';
import '../App.css';

const approvalMachine = createMachine({
    id: 'approve',
    initial: 'Not Submitted',
    context: {
        retries: 0
    },
    states: {
        'Not Submitted': {
            on: {
                SUBMIT: 'Pending Approval'
            }
        },
        'Pending Approval': {
            on: {
                CANCEL: 'Not Submitted',
                CHANGE: 'Change Request',
                DENIED: 'Denied',
                APPROVED: 'Approved'
            }
        },
        'Change Request': {
            on: {
                RESUBMITTED: 'Pending Approval',
                CANCEL: 'Not Submitted'
            }
        },
        Denied: {
            type: 'final'
        },
        Approved: {
            on: {
                PUBLISH: 'Published'
            }
        },
        Published: {
            type: "final"
        }
    }
});

function MagellanStateManager({id}) {
    const [service, setService] = useState(interpret(approvalMachine));
    const [counter, setCounter] = useState(0);

    useEffect(() => {
        // TODO: Add the fetch to get the stored state from the server
        const approvalService = interpret(approvalMachine);
        approvalService.start(approvalMachine.initialState);
        setService(approvalService);
        // TODO: Add dependencies for the useEffect for when identification values change
    }, []);

    function storeState(theEvent) {
        const newState = service.send(theEvent);
        const theState = JSON.stringify(newState);
        // TODO: Add the fetch to send the state to the server to be stored
        console.log(theState);
        setCounter(counter + 1);
    }

    function notEvent(theEvent) {
        if (service != null && service._state != null) {
            return !service._state.nextEvents.includes(theEvent);
        } else {
            return true;
        }
    }

    return (
        <span style={{float: "right", marginTop: 8}}>
            <span className="m-form-label  ml-3">State:</span> <span>{service ? service._state ? service._state.value : "" : ""}</span>
            <MagellanButton className="ml-3" disabled={notEvent('SUBMIT')} onClick={() => storeState('SUBMIT')}>Submit</MagellanButton>
            <MagellanButton className="ml-3" disabled={notEvent('CANCEL')} onClick={() => storeState('CANCEL')}>Cancel</MagellanButton>
            <MagellanButton className="ml-3" disabled={notEvent('CHANGE')} onClick={() => storeState('CHANGE')}>Change</MagellanButton>
            <MagellanButton className="ml-3" disabled={notEvent('RESUBMITTED')} onClick={() => storeState('RESUBMITTED')}>Resubmit</MagellanButton>
            <MagellanButton className="ml-3" disabled={notEvent('DENIED')} onClick={() => storeState('DENIED')}>Deny</MagellanButton>
            <MagellanButton className="ml-3" disabled={notEvent('APPROVED')} onClick={() => storeState('APPROVED')}>Approve</MagellanButton>
            <MagellanButton className="ml-3" disabled={notEvent('PUBLISH')} onClick={() => storeState('PUBLISH')}>Publish</MagellanButton>
        </span>
    )

}

export default MagellanStateManager;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法使用 xstate 恢复具有持久 state 的 state 机器并做出反应 - unable to restore state machine with persisted state using xstate and react 有没有办法使用从 Firebase 返回的 promise 初始化 Xstate state 机器? - Is there a way to initialize an Xstate state machine using a promise returned from Firebase? 如何在 React 的 useEffect 中设置状态? - How to set the state in useEffect in React? 如何获得分层xstate机器的初始状态? - How to get the initial state of a hierarchical xstate machine? 如何在 Xstate state 机器中保持 state 反应? - How to persist state in Xstate state machines in react? 使用useEffect渲染主要组件时,如何从本地存储中设置反应state? - How to set react state from local storage when rendering main component, using useEffect? State在react js中的useEffect之后没有设置 - State is not set after useEffect in react js 是否可以在 XState 机器中定义每个状态的转换 - 只需一次 - Is it possible to define in XState machine a transition from each state - just once React Native - Class 组件到功能组件(UseEffect:state 未定义) - React Native - Class Component to Functional Component (UseEffect: state undefined) 在React中将状态从一个组件设置到另一个组件的最佳实践方法 - Best practice way to set state from one component to another in React
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM