6

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

明确地说,通常会有一个初始状态对象和一个 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 调度函数来处理反应应用程序中的状态。

[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 来接受数组而不是字符串,然后映射到该数组。但这被认为是一种好习惯吗?

4

1 回答 1

9

如果您只想使用 dispatch 一次:

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

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-05-24T05:11:35.507 回答