範例是單純的線性步驟處理方式,會遇到一些問題。例如在 confirm step 我們不會希望回到 loading step,而是可以到 search step,但這樣就必須加入許多的判斷條件式,並且也難以進行維護。

const steps = ['search', 'loading', 'confirm', 'submit']
 
const [stepIndex, setStepIndex] = useState(0)
const currentStep = steps[stepIndex]
 
const nextStep = () => {
    steStepIndex(prev => prev + 1)
}
const prevStep = () => {
    steStepIndex(prev => prev - 1)
}

建立一個 step graph 可以更簡單的達成:

const stepGraph = {
    search: {
        next: 'loading',
    },
    loading: {
        next: "confirm"
    },
    confirm: {
        prev: "search",
        next: "submit"
    },
    submit: {
        prev: "confirm"
    }
}
 
const [currentStep, setCurrentStep] = useState('search')
 
const nextStep = () => {
    setCurrentStep(stepGraph[currentStep].next)
}
 
const prevStep = () => {
    setCurrentStep(stepGraph[currentStep].prev)
}

透過建立 step graph 可以輕鬆的達成非線性的步驟處理,也避免了許多不清晰的邏輯。