Operaciones de datos remotas React Grid
By default, the IgrGrid uses its own logic for performing data operations.
Puedes realizar estas tareas de forma remota y alimentar los datosIgrGrid resultantes aprovechando ciertas entradas y eventos que son expuestos por elIgrGrid.
Infinite Scroll
A popular design for scenarios requiring fetching data by chunks from an end-point is the so-called infinite scroll. For data grids, it is characterized by continuous increase of the loaded data triggered by the end-user scrolling all the way to the bottom. The next paragraphs explain how you can use the available API to easily achieve infinite scrolling in IgrGrid.
To implement infinite scroll, you have to fetch the data in chunks. The data that is already fetched should be stored locally and you have to determine the length of a chunk and how many chunks there are. You also have to keep a track of the last visible data row index in the grid. In this way, using the StartIndex and ChunkSize properties, you can determine if the user scrolls up and you have to show them already fetched data or scrolls down and you have to fetch more data from the end-point.
The first thing to do is fetch the first chunk of the data. Setting the totalItemCount property is important, as it allows the grid to size its scrollbar correctly.
Additionally, you have to subscribe to the DataPreLoad output, so that you can provide the data needed by the grid when it tries to display a different chunk, rather than the currently loaded one. In the event handler, you have to determine whether to fetch new data or return data, that's already cached locally.
Infinite Scroll Demo
Remote Paging
La función de localización puede funcionar con datos remotos. Para demostrar esto, primero declaremos que nuestro servicio será responsable de la obtención de datos. Necesitaremos el recuento de todos los elementos de datos para poder calcular el recuento de páginas. Esta lógica se agregará a nuestro servicio.
const CUSTOMERS_URL = `https://data-northwind.indigo.design/Customers/GetCustomersWithPage`;
export class RemoteService {
public static getDataWithPaging(pageIndex?: number, pageSize?: number) {
return fetch(this.buildUrl(CUSTOMERS_URL, pageIndex, pageSize))
.then((result) => result.json());
}
private static buildUrl(baseUrl: string, pageIndex?: number, pageSize?: number) {
let qS = "";
if (baseUrl) {
qS += `${baseUrl}`;
}
// Add pageIndex and size to the query string if they are defined
if (pageIndex !== undefined) {
qS += `?pageIndex=${pageIndex}`;
if (pageSize !== undefined) {
qS += `&size=${pageSize}`;
}
} else if (pageSize !== undefined) {
qS += `?perPage=${pageSize}`;
}
return `${qS}`;
}
}
After declaring the service, we need to create a component, which will be responsible for the IgrGrid construction and data subscription.
<IgrGrid
ref={grid}
data={data}
pagingMode="remote"
primaryKey="customerId"
height="600px"
isLoading={isLoading}
>
<IgrPaginator
perPage={perPage}
ref={paginator}
onPageChange={onPageNumberChange}
onPerPageChange={onPageSizeChange}>
</IgrPaginator>
<IgrColumn field="customerId" hidden={true}></IgrColumn>
<IgrColumn field="companyName" header="Company Name"></IgrColumn>
<IgrColumn field="contactName" header="Contact Name"></IgrColumn>
<IgrColumn field="contactTitle" header="Contact Title"></IgrColumn>
<IgrColumn field="address.country" header="Country"></IgrColumn>
<IgrColumn field="address.phone" header="Phone"></IgrColumn>
</IgrGrid>
A continuación, configure el estado:
const grid = useRef<IgrGrid>(null);
const paginator = useRef<IgrPaginator>(null);
const [data, setData] = useState([]);
const [page, setPage] = useState(0);
const [perPage, setPerPage] = useState(15);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
loadGridData(page, perPage);
}, [page, perPage]);
y finalmente configure el método para cargar los datos:
function loadGridData(pageIndex?: number, pageSize?: number) {
// Set loading state
setIsLoading(true);
// Fetch data
RemoteService.getDataWithPaging(pageIndex, pageSize)
.then((response: CustomersWithPageResponseModel) => {
setData(response.items);
// Stop loading when data is retrieved
setIsLoading(false);
paginator.current.totalRecords = response.totalRecordsCount;
})
.catch((error) => {
console.error(error.message);
setData([]);
// Stop loading even if error occurs. Prevents endless loading
setIsLoading(false);
})
}
Para obtener más información, consulte la muestra completa a continuación:
Grid Remote Paging Demo
y, por último, configura el comportamiento de las RowIslands:
Known Issues and Limitations
- Cuando la cuadrícula no
primaryKeytiene un sistema fijo y los escenarios de datos remotos están habilitados (al paginar, ordenar, filtrar o desplazar las solicitudes de disparo a un servidor remoto para recuperar los datos que se mostrarán en la cuadrícula), una fila perderá el siguiente estado tras completar una solicitud de datos:
- Selección de fila
- Fila Expandir/contraer
- Edición de filas
- Fijación de filas
API References
Additional Resources
- Paginación
- Virtualización y rendimiento
- Filtración
- Clasificación
- resúmenes
- Columna en movimiento
- Fijación de columnas
- Cambio de tamaño de columna
- Selección
Nuestra comunidad es activa y siempre da la bienvenida a nuevas ideas.