React Hooks 如何优雅地更新数组

现在每到需要更新数组我就得复制黏贴这样的代码,有更好的办法么

const handleFieldsChange = (value: [], record: Tables_Fields, index: number) => {
    const source = [...dataSource_A];
    source.splice( index, 1, { ...record, ui_value: value });
    setDataSource_A(source)
  };

  const handleMessageChange = (value: string, record: Tables_Fields, index: number) => {
    const source = [...dataSource_B];
    source.splice( index, 1, { ...record, message: value });
    setDataSource_B(source)
  };
阅读 2.2k
1 个回答

你好,你给的代码信息不是很全,现在根据你的描述,感觉可以简化成这样:

  // 定义
  const handleChange = (index: number, modify: object) => {
    setDataSource((list) => {
      return list.map((item, _index) => {
        return index === _index ? { ...item, ...modify } : item;
      });
    });
  };
  // 使用
  handleChange(2, { message: 'xxx' });
  handleChange(2, { ui_value: 'xxx' });

希望对你有所帮助!

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题