【问题标题】:Sending multiple actions with useReducers dispatch function?使用 useReducers 调度功能发送多个操作?
【发布时间】:2020-09-10 20:57:40
【问题描述】:

在 react 中使用 useReducer 钩子时,是否可以使用 dispatch 函数发送多个操作?我尝试将一系列操作传递给它,但这会引发未处理的运行时异常。

明确地说,通常会有一个初始状态对象和一个 reducer,如下所示:

const initialState = { message1: null, message2: null }

const messageReducer = (state, action) => {
  switch(action.type) {
    case SET_MESSAGE1:
      return {...state, message1: action.payload.message1}
    case SET_MESSAGE2:
      return {...state, message2: action.payload.message2}
    default:
      throw new Error("Something went wrong!")
  }
}

然后可以像这样使用 useReducers 调度函数来处理 React 应用程序中的状态。

[state, dispatch] = useReducer(messageReducer, initialState)
...
dispatch({type: SET_MESSAGE1: payload: {message1: "setting message1"})
dispatch({type: SET_MESSAGE2: payload: {message2: "setting message2"})

我想做的是将这两个突变发送到一个数组中,这样我只需要调用一次调度,如下所示:

dispatch([
  {type: SET_MESSAGE1: payload: {message1: "setting message1"},
  {type: SET_MESSAGE2: payload: {message2: "setting message2"}
])

现在我写下来了,我意识到从技术上讲,我可以编写 reducer 来接受数组而不是字符串,然后映射到该数组。但这算是一种好的做法吗?

【问题讨论】:

    标签: javascript reactjs react-hooks use-reducer


    【解决方案1】:

    如果你只想使用 dispatch 一次:

    您可以在 reducer 中再添加一个 switch case SET_MULTIPLE

    const messageReducer = (state, action) => {
      switch(action.type) {
        case SET_MESSAGE1:
          return {...state, message1: action.payload.message1}
        case SET_MESSAGE2:
          return {...state, message2: action.payload.message2}
        case SET_MULTIPLE:
          return {...state, ...action.payload } // <---- HERE
        default:
          throw new Error("Something went wrong!")
      }
    }
    

    然后像这样改变调度:

    dispatch({type: SET_MULTIPLE , payload: {message1: "setting message1" , message2 : "setting message2"})
    

    【讨论】:

      猜你喜欢
      • 2020-11-16
      • 2016-09-23
      • 2021-07-09
      • 1970-01-01
      • 1970-01-01
      • 2020-01-13
      • 2021-10-30
      • 2014-02-19
      • 2019-02-19
      相关资源
      最近更新 更多