【问题标题】:Reducer return undefined in data update数据更新中减速器返回未定义
【发布时间】:2021-07-18 18:38:53
【问题描述】:

我正在尝试创建一个 reducer 以在调用某个操作后删除对象,但我无法更新并将新对象保存在我的数据中

减速机:

export default function deleteCard(state = INITIAL_STATE, action: any) {
  if (action.type === 'DELETE_CARD') {
    return state.data.filter((card: Card) => card.cardId !== action.id)
  } else {
    return state
  }
}

操作删除卡片

export const deleteCardAction = (id: number) => {
  return {
    type: 'DELETE_CARD',
    id: id
  }
}

函数 handleDeleteCard()

 const cards = useSelector((state: RootStateOrAny) => state.createCard.data);
  const dispatch = useDispatch();

  function handleDeleteCard() {
    cards.map(({ cardId }: Card) => {     
      if (cardId === props.activeCard ) {
        dispatch(deleteCardAction(cardId))
      }
    })
  }

Initial State:

  export const INITIAL_STATE = {
  activeCard: 0,
  data: [
    {
      cardId: 0,
      cardName: 'Credit card',
      cardUsername: 'Vanzo',
      cardNumber: '1234 1234 1234 1234',
      hideCardNumber: false,
    },
  ]
}

我尝试更新时出现以下错误:

TypeError: undefined is not an object (evaluating 'state.data.filter')  

【问题讨论】:

  • 您如何使用deleteCard 减速器?它似乎没有收到状态,但我们不知道为什么不看看你是如何使用它的。
  • 我已经更新了执行 reducer 的部分代码
  • 您需要在每个 reducer 案例中返回整个状态。您只是返回过滤后的 state.data 数组,因此现在成为状态。
  • @PORMAZION 谢谢,下面给出的答案应该可以解决问题,这绝对是个好建议。

标签: reactjs react-native redux react-redux reducers


【解决方案1】:

要更新状态,您需要从 reducer 返回整个状态,如下所示:

export default function deleteCard(state = INITIAL_STATE, action: any) {
  if (action.type === 'DELETE_CARD') {
    return {
        ...state,
        data: state.data.filter((card: Card) => card.cardId !== action.id)
    }
  } else {
    return state
  }
}

【讨论】:

    猜你喜欢
    • 2019-07-05
    • 1970-01-01
    • 2017-10-18
    • 2020-04-08
    • 1970-01-01
    • 1970-01-01
    • 2020-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多