简体   繁体   English

Ag-Grid 在动态添加行时不会导航到下一页

[英]Ag-Grid does not navigate to next page on adding row dynamically

I am using Ag-grid used in my React app mapped to some state.我正在使用我的 React 应用程序中使用的 Ag-grid 映射到一些 state。

const [myGridData, setMyGridData] = useState([]);

<MyAgGrid
    rowData={myGridData}
    pagination
    paginationPageSize={5}
    {...props}
/>

Now, I have a form which takes user input and adds a new row dynamically to the grid.现在,我有一个表单,它接受用户输入并向网格动态添加一个新行。

So on saving this form, below code is invoked因此,在保存此表单时,将调用以下代码

setMyGridData(current => [...current, newRowData]);
if (gridApi && gridApi.getDisplayedRowCount() >= gridApi.paginationGetPageSize()) {
    gridApi.paginationGoToPage(parseInt((gridApi.getDisplayedRowCount() / gridApi.paginationGetPageSize())) + 1);
}

The page size is set to 5. So while I save the 6th record, I want that the grid navigate to page 2 programatically, so that the user sees the new record in the grid.页面大小设置为 5。因此,当我保存第 6 条记录时,我希望网格以编程方式导航到第 2 页,以便用户在网格中看到新记录。

But here while the grid does add the 6th row, it does not navigate to page 2 and I have to navigate manually to see the 6th record.但是在这里,虽然网格确实添加了第 6 行,但它没有导航到第 2 页,我必须手动导航才能看到第 6 条记录。 However, if I am on page 1 and add the next record (ie 7th row), it then does navigate to page 2.但是,如果我在第 1 页并添加下一条记录(即第 7 行),它会导航到第 2 页。

So it seems like that for the 6th record, the 2nd page is not yet ready/created.因此,对于第 6 条记录,第 2 页似乎尚未准备好/创建。

Please help.请帮忙。

React state won't have flowed into the ag-grid component immediately after calling the setState function, due the nature of the react lifecycle.由于反应生命周期的性质,在调用 setState function 后,反应 state 不会立即流入农业网格组件。 (This means that ag-grid won't know it has that extra row yet at the time you're calling the function) (这意味着 ag-grid 在您调用该函数时还不知道它有额外的行)

You could skip the react lifecycle and instead set the row data directly into the grid with api.setRowData, however the approach which leans more into the react lifecycle would be to instead use an effect like so:您可以跳过反应生命周期,而是使用 api.setRowData 将行数据直接设置到网格中,但是更倾向于反应生命周期的方法是使用如下效果:

const [myGridData, setMyGridData] = useState([]);

useLayoutEffect(() => {
    gridApi.paginationGoToPage(parseInt((gridApi.getDisplayedRowCount() / gridApi.paginationGetPageSize())) + 1);
}, [myGridData]);

<MyAgGrid
    rowData={myGridData}
    pagination
    paginationPageSize={5}
    {...props}
/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM