首页 > 解决方案 > useReducer 可以与状态数组一起使用吗?

问题描述

我已经实现了一种相当简单的方法来添加撤消,useReducer如下所示:

export const stateMiddleware = reducerFunc => {
  return function(state = { history: [] }, action) {
    return {
      history:
        action.type === UNDO
          ? drop(state.history) // lodash drop
          : [reducerFunc(state.history[0], action), ...state.history],
    }
  }
}

const [state, dispatch] = useReducer(stateMiddleware(reducer), { history: [initialState] })

state变量包含整个历史记录,因此必须从第一个元素中提取当前状态。

我想知道是否useReducer会接受state参数数组(也欢迎对我的方法发表评论 - 它避免使用看起来很重的包来做类似的事情)

标签: javascriptreactjsreact-hooks

解决方案


如果您真正要问的是是否可以useReducer使用普通数组初始化钩子状态,那么可以。

编辑 useReducer-with-array


推荐阅读