You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript Reducer删除数据后无法更新状态,如何正确赋值过滤数据?

解决TypeScript Reducer删除数组元素的状态更新错误

问题场景

用TypeScript结合React Reducer处理联系人数组删除操作时,遇到类型不匹配错误,导致状态无法正常更新。

错误信息

Type '{ newData: Contactos[]; contacts: Contactos[]; }' is not assignable to type 'ContactsState'. Object literal may only specify known properties, and 'newData' does not exist in type 'ContactsState'.

问题代码

import React from 'react';

interface Contactos {
  id: number;
  name: string;
  email: string;
  phone: string;
}

interface ContactsState {
  contacts: Contactos[];
}

type ContactsReducerAction = {
  type: 'delete';
  payload: {
    id: number;
  };
};

const INITIAL_STATE = [
  {
    id: 1,
    name: 'John Doe',
    email: 'jdoe@gmail.com',
    phone: '555-555-5555',
  },
  {
    id: 2,
    name: 'Karen Williams',
    email: 'Karen@gmail.com',
    phone: '222-222-2222',
  },
  {
    id: 3,
    name: 'Henry Johnson',
    email: 'henry@gmail.com',
    phone: '111-111-1111',
  },
];

export const contactsReducer = (
  state: ContactsState,
  action: ContactsReducerAction
): ContactsState => {
  switch (action.type) {
    case 'delete': {
      let newData = state.contacts.filter(el => el.id !== action.payload.id);

      return {
        ...state,
        newData,
      };
    }

    default:
      return state;
  }
};

修复方案

错误根源是Reducer返回的对象里用了newData作为属性名,但ContactsState接口只定义了contacts属性。需要把过滤后的数组赋值给contacts属性,而非新增不存在的属性。

修改后的Reducer代码:

export const contactsReducer = (
  state: ContactsState,
  action: ContactsReducerAction
): ContactsState => {
  switch (action.type) {
    case 'delete': {
      const filteredContacts = state.contacts.filter(el => el.id !== action.payload.id);

      return {
        ...state,
        contacts: filteredContacts,
      };
    }

    default:
      return state;
  }
};

另外,INITIAL_STATE的类型也需要修正——当前它是纯数组类型,但ContactsState是包含contacts属性的对象,初始化时要改成:

const INITIAL_STATE: ContactsState = {
  contacts: [
    {
      id: 1,
      name: 'John Doe',
      email: 'jdoe@gmail.com',
      phone: '555-555-5555',
    },
    {
      id: 2,
      name: 'Karen Williams',
      email: 'Karen@gmail.com',
      phone: '222-222-2222',
    },
    {
      id: 3,
      name: 'Henry Johnson',
      email: 'henry@gmail.com',
      phone: '111-111-1111',
    },
  ],
};

补充说明

  • Reducer必须返回符合ContactsState类型的对象,不能添加接口中未定义的属性。
  • 用扩展运算符...state保留原状态的其他属性(方便后续扩展状态结构),同时把contacts更新为过滤后的数组。

内容的提问来源于stack exchange,提问作者user15500092

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 12:03:37