对前端状态管理的个人理解

2,260 阅读3分钟

前端状态管理请三思 在这篇文章中提到了前端状态管理的一种思路,也就是使用有限状态自动机来管理前端状态。初读时我没有深入思考以至于鲁莽的认为又是一篇描述函数式中的条件执行来替代 switch 的文章,进而给出了想当然的回复,非常不好意思,所以知耻后苦搜索相关的内容,在 ReactRally2017 视频中找到 David Khourshid - Infinitely Better UIs with Finite Automata 这个研报。David 在视频中详细分析了有限状态自动机在 UI 状态管理中的应用,并给出了自己的解决方案 XState 。大家可以自行查找学习,我在这里只是给出个人对前端状态管理的理解和应用。

前端状态

redux 是 react 技术栈中的状态控制流框架,使用了标准的函数式思想,期望(强制)所有状态管理都是纯函数。这也意味着各状态之间都是独立的。但是有一类状态 redux 直接甩给了的第三方模块,副作用模块 redux-saga 也就成了任劳任怨的典型代表。副作用正是因为不确定性和可变性而得名,而其给出的状态又是相互影响,如何解耦使得原本复杂的非线性呈现为线性逻辑,正是有限状态自动机的用武之处。所以个人理解应在 saga 中使用状态管理。

简单实现

本人初学前端,下面实例和语句基本靠蒙未必正确,欢迎指正,特此声明。
首先给出应用环境: 登录流程。

登录流程
登录流程

对应的代码如下:

const machineState = {
  currentState: 'login_screen',
  states: {
    login_screen: {
      login: 'loading'
    },
    loading: {
      success: 'main_screen',
      failure: 'error'
    },
    main_screen: {
      logout: 'login_screen',
      failure: 'error'
    },
    error: {
      login: 'loading'
    }
  }
}

因为在 saga 中应用,所以给出状态所对应 effects

function * mainScreenEffects() {
  yield put({ type: SET_AUTH, payload: true })
  yield put(NavigationActions.navigate({ routeName: 'Main' }))
  yield put({ type: SET_LOADING, payload: { scope: 'login', loading: false } })
}

function * errorEffects(error) {
  yield put({ type: REQUEST_ERROR, payload: error.message })
  yield put({ type: SET_LOADING, payload: { scope: 'login', loading: false } })
}
const effects = {
  loading: () =>
    put({
      type: SET_LOADING,
      payload: { scope: 'login', loading: true }
    }),
  main_screen: () => mainScreenEffects(),
  error: error => errorEffects(error),
  login_screen: () => put({ type: SET_AUTH, payload: false })
}

上述 effects 都是触发更新 UI 的 actions

最后编写有限状态自动机将状态和 effects 关联,借鉴的 redux:

const Machine = (state, effects) => {
  let machineState = state
  // 转换状态函数
  function transition(state, operation) {
    const currentState = state.currentState
    const nextState = state.states[currentState][operation]
      ? state.states[currentState][operation]
      : currentState
    return { ...state, currentState: nextState }
  }
  // 转换状态的接口
  function operation(name) {
    machineState = transition(machineState, name)
  }
  // 获取当前状态
  function getCurrentState() {
    return machineState.currentState
  }
  // 输出 effects
  const getEffect = name => (...arg) => {
    operation(name)
    return effects[machineState.currentState](...arg)
  }
  return { operation, getCurrentState, getEffect }
}

export default Machine

实例应用

现在将上述的状态机应用在登录流程中:

const machine = Machine(machineState, effects)
const loginEffect = machine.getEffect('login')
const failureEffect = machine.getEffect('failure')
const successEffect = machine.getEffect('success')

export function * loginFlow() {
  while (true) {
    const action = yield take(LOGIN_REQUEST)
    const username = action.payload.get('username')
    const password = action.payload.get('password')
    yield loginEffect()
    try {
      let isAuth = yield call(Api.login, { username, password })
      if (isAuth) {
        yield successEffect()
        console.log(machine.getCurrentState())
      }
    } catch (error) {
      yield failureEffect(error)
    } finally {
        // .......
    }
  }
}

自我感觉现在状态管理的思路比以前清晰了,当然这也许是假象,还是请指正。结束前谢谢 前端状态管理请三思 的作者和译者。