如何在状态更新前检查动作有效负载?

时间:2020-07-20 01:34:07

标签: javascript redux react-redux

我正在为第一个react-redux应用程序学习redux。在更改状态之前,我如何设法验证有效载荷值?例如下面的代码:

todoExample = {name: 'learn redux', author: 'myself'}
wrongTodoExample = {name: 'learn redux'}

dispatch(addTodos({todo: todoExample})) 
dispatch(addTodos({todo: wrongTodoExample }))

使用上面的代码,我向状态添加了2个待办事项,但是它们没有相同的键。

是否有一种方法可以检查有效载荷值以授权我的reducer中的第一个addTodos而不是第二个addTodos? 我已经在互联网上搜索了,但找不到答案。抱歉,如果我的问题多余。

4 个答案:

答案 0 :(得分:1)

您可以使用redux中间件来验证事物,这绝对是中间件预期的用例之一。任何中间件都可以检查和修改流经管道的任何动作,然后再到达减速器,甚至阻止动作继续进行。

const verifyPayload = store => next => action => {
  if (isVerifyPayload(action.payload)) {
    return next(action);
  } else {
    return store.dispatch({ type: 'NOT_AUTHORIZED' })
  }
  
}

const store = createStore(
 initialState,
 applyMiddleware(verifyPayload)
)

答案 1 :(得分:0)

same key的描述不清楚,您的意思是姓名或作者,还是其他特定的键,例如code \ id。
您可以尝试在派遣前或在addTodos

内验证待办事项
function addTodos(payload) {
  if (!payload.todo.code) return;
  // simply return,
  // otherwise throw an error to indicate that your todos miss a specific key
}

答案 2 :(得分:0)

您可以在化简器中使用三元运算符以及一些util函数来验证待办事项。如果待办事项有效,则将您的状态转换为包括新待办事项,如果未返回相同状态(实际上什么也不做)。

const isValidTodo = (todo) => {
    //Implement your validations. E.g: A valid todo will have a name and an author
    return todo.name && todo.author;
}

const todos = (state = [], action) => {
  switch (action.type) {
    case 'ADD_TODO':
      return isValidTodo(action.payload) ?
      [
        ...state,
        {
          name: action.payload.name,
          author: action.payload.text,
          completed: false
        }
      ] 
   : state
    default:
      return state
  }
}

答案 3 :(得分:0)

我找到了一种非常适合我的需求的解决方案,它是TypeScript。现在,我有了“有效负载类型”,可以让我定义我在action.payload中需要的键,而无需任何验证功能。

非常感谢您的支持。