【问题标题】:Mobx Store does not update rows in AGGridMobx Store 不更新 AGGrid 中的行
【发布时间】:2023-01-19 22:43:12
【问题描述】:

我想使用 mobx store 进行状态管理。我想更新商店中的记录,它应该反映在网格中。我有更新商店的方法 updateRecord 但 AGgrid 没有得到更新。另一种方法 deleteRecord 工作得很好,它更新存储和网格。

我尝试了两种方法来更新商店,但都不起作用。

this.gridData[index] = { id: 1, name: 'XX John' } //update the complete object
this.gridData[index].name = 'XX John'; // update specific property of object

如何使 updateRecord 方法起作用?请提供任何指示。

完整的源代码。

import React, { useState } from 'react';

import { observable, action, makeAutoObservable } from 'mobx';
import { AgGridReact } from 'ag-grid-react';

import 'ag-grid-community/dist/styles/ag-grid.css';
import 'ag-grid-community/dist/styles/ag-theme-alpine.css';
import { observer } from 'mobx-react-lite';

interface IEmployee {
  id: number;
  name: string;
}

class MyStore {
  gridData: IEmployee[] = [
    { id: 1, name: 'John' },
    { id: 2, name: 'Jane' }
  ];

  constructor() {
    makeAutoObservable(this, {
      gridData: observable,
      updateRecord: action,
      deleteRecord: action
    });
  }

  updateRecord(id: number, newData: { name: string }) {
    const index = this.gridData.findIndex((record) => record.id === id);
    //this.gridData[index] = { id: 1, name: 'XX John' }
    //this.gridData[index].name = 'XX John';
  }

  deleteRecord(id: number) {
    this.gridData = this.gridData.filter((record) => record.id !== id);
  }
}

const store = new MyStore();

const MyComponent = observer(() => {
  const [colDefs, setColDefs] = useState([{ field: 'id' }, { field: 'name' }]);

  const { gridData } = store;

  return (
    <div>
      <div className="ag-theme-alpine" style={{ height: 400, width: 600 }}>
        <AgGridReact rowData={gridData} columnDefs={colDefs}></AgGridReact>
      </div>
      <button onClick={() => store.updateRecord(1, { name: 'Updated John' })}>
        Update record
      </button>
      <button onClick={() => store.deleteRecord(2)}>Delete record</button>
    </div>
  );
})

【问题讨论】:

    标签: ag-grid mobx mobx-react mobx-react-lite


    【解决方案1】:

    AgGridReact 可能仅在 rowData (gridData) 完全更改(更改引用)时更新,它可能不知道某些内部对象的某些属性已更新。

    我认为最简单的方法是使用 toJS (https://mobx.js.org/api.html#tojs) MobX 方法将您的可观察值转换为常规 JS 对象。

    <AgGridReact rowData={toJS(gridData)} columnDefs={colDefs}></AgGridReact>
    

    您的 deleteRecord 方法有效,因为您使用 .filter() 创建了新的 gridData 数组

    【讨论】:

      猜你喜欢
      • 2019-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-18
      • 2022-08-20
      • 2021-01-10
      • 2020-08-31
      • 1970-01-01
      相关资源
      最近更新 更多