Ag-Grid-React 修改CellRenderer组件中的数据后更新网格中的rowData

问题描述 投票:0回答:0

我有一个问题,在 cellRenderer 组件完成操作后,我无法更新 ag-grid React 中的 rowData。 网格包含银行账户列表,看起来像: enter image description here 我在每一行都有“编辑”和“删除”按钮。我在一个新的 React 组件(文件)中表示它们。

  • 当我们单击删除按钮时 => 它会从网格中删除该行,但我不知道如何更新 **rowData ** 以便通过 axios post 调用将其发送到我的后端 api。
  • 当我们点击编辑按钮(铅笔)=> 它会显示一个带有更多账户行数据的模式。由于每个帐户都有一个 ibans 列表,因此我在双列表框中显示此模式中的 ibans 列表(https://www.npmjs.com/package/react-dual-listbox)。在双列表框中,我在右侧列出了所有 ibans,在左侧列出了该帐户的现有 ibans。最后,我想用选定的 ibans 更新 **rowData **。

我的问题是如何更新 agGrid 后面的 **rowData **。 ag-grid 状态的更新适用于 applyTransaction。 这里有一些代码:

MyGridBank.tsx :

 import React, {useEffect, useRef, useState} from 'react';
import axios from "axios";
import EditDeleteAccountRenderer from './renderers/EditDeleteAccountRenderer’;

 export const MyGridBank : React.FC = () => {

const url ='https://something-to-display'

const [gridApi, setGridApi] = useState(null);
const [gridColumnApi, setGridColumnApi] = useState(null);
const gridRef = useRef<AgGridReact>(null);
const [rowData, setRowData] = useState([]) //I have a list of accounts that I get via axios call
/*One account has the following structure:
        {  
           "id":234323,  => I don’t display the id in the ag-grid
            "name": "AxseRe",
            "cityName": "London",
            "bankId": "AS4567GF68000SS3",
            "listIban": [
              {"firstIbanId": 4534 , "firstIbanValue": "A34"},
              {"firstIbanId": 4535 , "firstIbanValue": "A35"},
              {"firstIbanId": 4536 , "firstIbanValue": "A36"},
              {"firstIbanId": 4537 , "firstIbanValue": "A37"}
                  ]  => I don’t display the listIban in the ag-grid but I use it to display in a dual-list-box in a Modal which gets opened when clicking on a button pencil via CellRenderer 
}*/

const [frameworkComponents, setFrameworkComponents] = useState({
        editDeleteAccount: EditDeleteAccountRenderer })
    
const gridOptions = {
        columnDefs: [
            {headerName: "Name", field: 'name', wrapText: true},
            {headerName: "City Name", field: 'cityName', wrapText: true },
            {headerName: "Id Bank", field: 'bankId', wrapText: true},
            {headerName: 'Actions', field: '',wrapText: true, cellRenderer: "editDeleteAccount"}
        ],
        defaultColDef: {
            flex: 1,
            filter: 'agTextColumnFilter',
            animateRows: true,
            wrapText:true
        },
    };

const onGridReady = (params) => {
        setGridApi(params.api);
        setGridColumnApi(params.columnApi);
    }
    
const getData = () => {
        axios.get(url).then((result)=>{
            setRowData(result.data);
        }).catch((error) => {
            console.log(error);
        });
    }

    useEffect(() => {
       getData
    }, []);
    
return(
    <div className="ag-theme-alpine-dark" style={{height: "870px",width:"100%"}}>
                                <AgGridReact
                                onGridReady={onGridReady}
                                rowData={**rowData**}
                                columnDefs={gridOptions.columnDefs}
                                defaultColDef={gridOptions.defaultColDef}
                                frameworkComponents={frameworkComponents}
                                ref={gridRef}
                                rowSelection={'single'}
                                pagination={true}
                                paginationPageSize={5}
                                >
                                </AgGridReact>
                            </div>
)       
}

我将渲染器作为另一个组件:

EditDeleteAccountRenderer.tsx :

 import React from "react";
import ModeIcon from '@mui/icons-material/Mode';
import DeleteForeverOutlinedIcon from "@mui/icons-material/DeleteForeverOutlined";
import {blue, red} from "@mui/material/colors";

import Modal from 'react-modal';


 
export class EditDeleteAccountRenderer extends React.Component {
    props: any;
    accountDataDetails = new Map();
    id: any; //to get "id" by the props from the data grid defined in MyGridBank.tsx
    name: any; //to get "name" by the props from the data grid defined in MyGridBank.tsx
    cityName: any; //to get "cityName" by the props from the data grid defined in MyGridBank.tsx
    bankId: any; //to get "bankId" by the props from the data grid defined in MyGridBank.tsx
    /*just to remind that one row in the grid rowData is represented with the following data:             
        {  
           "id":234323,
            "name": "AxseRe",
            "cityName": "London",
            "bankId": "AS4567GF68000SS3",
            "listIban": [
                {"firstIbanId": 4534 , "firstIbanValue": "A34"},
                {"firstIbanId": 4535 , "firstIbanValue": "A35"},
                {"firstIbanId": 4536 , "firstIbanValue": "A36"},
                {"firstIbanId": 4537 , "firstIbanValue": "A37"}]
}*/
    urlBackendApi: string = ” https://something-to-display”

    state = {
        isModalOpen: false, //the modal in which I display the details of one Account 
        listIban : [],
        selected:[] //selected options 
        allIbans : [] 
    }
    
    onChangeBankId = (e) => {
       //HOW to update the rowData with the new entered value 'e.target.value' in MyGridBank.tsx ? 
       //I want to update the 'bankId' value in the rowData from MyGridBank.tsx for this id (row)
        console.log(e.target.value)
    }
    
    onEditRowDataInModal = (e) => {
        let data = this.props.data;
        let id = data.id
        let acount = JSON.stringify(data, ['id', 'cityName', 'name', 'bankId']);
        let accountToJson = JSON.parse(account)
        for (let property of Object.getOwnPropertyNames(accountToJson)) {
            this.accountDetails.set(property, accountToJson[property]);
            this.id = this.accountDetails.get('id')
            this.cityName = this.accountDetails.get('cityName')
            this.name = this.accountDetails.get('name')
            this.bankId = this.accountDetails.get('bankId')
        }
        //get the existing ibans from a backend service:
        axios.get(this.urlBackendApi+`${id}/ibans`).then((result) => {
                this.setState({selected : result.data})
            }).catch((error) => {console.log(error)})
        //get all ibans from a backend service:
        axios.get(this.urlBackendApi+`allIbans`).then((result) => {
                this.setState({allIbans : result.data})
            }).catch((error) => {console.log(error)})
        let ibans = data.ibans ;
        this.setState({ listIban: ibans });
        this.setState({isModalOpen: true}) 
        };
        
    closeModal = () => {
        this.setState({isModalOpen: false})
    };

   onDeleteRow = (e) => {
        let rowToDelete = this.props.node.data;
        e.gridOptionsWrapper.gridOptions.api.applyTransaction({ remove: [rowToDelete] });  // this works, the state of the grid data is updated visually, but not the “rowData” that populates the grid in MyGridBank.tsx. How could I update the state of the rowData (=> setRowData)??
console.log(e.gridOptionsWrapper.gridOptions.rowData) //I can display the rowData with this, but how to update its state?
    }
    
    buildListIbans = (selected) => {
    //--- here the function that constructs the new list of ibans already existing and the new selected where I update the state of this.state.listIban ---
    //Let's say that here I've constructed the new list and it looks like :
    /*
    *[{"firstIbanId": 4534 , "firstIbanValue": "A34"},{"firstIbanId": 4535 , "firstIbanValue": "A35"},{"firstIbanId": 4536 , "firstIbanValue": "A36"},{"firstIbanId": 4537 , "firstIbanValue": "A37"}, {"firstIbanId": 4539 , "firstIbanValue": "A39"}]
    */
    //How then I could update the rowData with the new state of listIban in MyGridBank.tsx??
    }

    handleSelectedIbans = (selectedOptions) => {
        this.setState({selected: selectedOptions})
        this.buildListIbans(selectedOptions)        
    }
    
    render() {
        return(
            <>
                <div className="col" style={{alignSelf: "center"}}>
                <Button onClick={() => this.onEditRowDataInModal(this.props.node)}><ModeIcon fontSize="small" sx={{color: blue[500]}}/></Button>
                <Button><DeleteForeverOutlinedIcon onClick={() => this.onDeleteRow(this.props.node)} fontSize="small" sx={{color: red[500]}}/></Button>                                                
                <div className="row">
                        <Modal isOpen={this.state.isModalOpen} onRequestClose={this.closeModal}>
                            <h3 style={{textAlign: "center"}}>Edit Fund</h3> <br/><br/>
                            <div className="col">
                                <h5> City Name: <i style={{fontWeight: "normal"}}>{this.cityName}</i></h5>
                            </div>
                            <br/>
                            <div className="col">
                                <h5> Name: <i style={{fontWeight: "normal"}}>{this.name}</i></h5>
                            </div>
                            <br/>
                            <div className="col">
                                <h5>Bank ID: <i style={{fontWeight: "normal"}}><input
                                    defaultValue={this.bankId} onChange={this.onChangeBankId}>{this.bankId}</input></i></h5>
                            </div>
                            <div className="row">
                                <div className="col-sm-4">
                                    <DualListBox
                                        options={this.state.allIbans.map((option: any) => ({
                                            value: option.firstIbanId,
                                            label: option.firstIbanValue,
                                        }))}
                                        selected={this.state.selected}
                                        onChange={this.handleSelectedIbans}
                                    />
                                </div>
                            </div>
                        </Modal>
                </div>
                </div>  
            </>
        );}}

我将不胜感激任何帮助或指示

我希望在 gridOptions.api.applyTransaction 之后更新 rowData; 我看到即使网格在视觉上更新,e.gridOptionsWrapper.gridOptions.rowData 在 EditDeleteAccountRenderer.tsx#onDeleteRow(e)

中保持不变
reactjs ag-grid ag-grid-react
© www.soinside.com 2019 - 2024. All rights reserved.