Fluent UI DetailsList仅显示30条数据,200条接口返回数据未全部展示
问题原因及解决方案
核心问题:类组件未同步Props更新
你的Job类组件仅在挂载阶段(constructor执行时)将传入的props.jobs赋值给state和_allItems,但当父组件App通过异步fetch获取到完整的200条数据后,props.jobs会更新,此时类组件不会自动同步更新内部state,导致DetailsList始终渲染初始的旧数据。
解决方案1:添加Props更新监听(类组件方案)
在Job组件中添加componentDidUpdate生命周期钩子,监听props.jobs的变化,同步更新内部状态:
export default class Job extends React.Component<IDetailsListBasicExampleProps, IDetailsListBasicExampleState> { // ... 现有代码 ... componentDidUpdate(prevProps: IDetailsListBasicExampleProps) { // 对比前后props的jobs是否变化 if (prevProps.jobs !== this.props.jobs) { this._allItems = this.props.jobs; this.setState({ items: this._allItems }); } } // ... 现有代码 ... }
解决方案2:改用函数组件(更推荐)
函数组件会自动响应props变化,无需手动处理生命周期,代码更简洁:
import * as React from "react"; import { DetailsList, DetailsListLayoutMode, IColumn } from '@fluentui/react/lib/DetailsList'; import { IJob } from "../interfaces/IJob.interfaces"; export interface IDetailsListBasicExampleProps { jobs: IJob[]; } const Job: React.FC<IDetailsListBasicExampleProps> = ({ jobs }) => { const columns: IColumn[] = [ { key: 'column1', name: 'Identifier', fieldName: 'Identifier', minWidth: 100, maxWidth: 200, isResizable: true }, { key: 'column2', name: 'ObjectType', fieldName: 'ObjectType', minWidth: 100, maxWidth: 200, isResizable: true }, { key: 'column3', name: 'InitialOnboardingTime', fieldName: 'InitialOnboardingTime', minWidth: 100, maxWidth: 200, isResizable: true }, { key: 'column4', name: 'LastAttemptedRunTime', fieldName: 'LastAttemptedRunTime', minWidth: 100, maxWidth: 200, isResizable: true }, { key: 'column5', name: 'LastSuccessfulRuntime', fieldName: 'LastSuccessfulRuntime', minWidth: 100, maxWidth: 200, isResizable: true }, { key: 'column6', name: 'EstimatedNextRuntime', fieldName: 'EstimatedNextRuntime', minWidth: 100, maxWidth: 200, isResizable: true }, { key: 'column7', name: 'Status', fieldName: 'Status', minWidth: 100, maxWidth: 200, isResizable: true }, { key: 'column8', name: 'ThresholdIncrease', fieldName: 'ThresholdIncrease', minWidth: 100, maxWidth: 200, isResizable: true }, { key: 'column9', name: 'ThresholdDecrease', fieldName: 'ThresholdDecrease', minWidth: 100, maxWidth: 200, isResizable: true }, ]; return ( <div> <div>{jobs.length}</div> <br /> <DetailsList items={jobs} columns={columns} setKey="set" layoutMode={DetailsListLayoutMode.justified} selectionPreservedOnEmptyClick={true} ariaLabelForSelectionColumn="Toggle selection" ariaLabelForSelectAllCheckbox="Toggle selection for all items" checkButtonAriaLabel="select row" /> <br /> </div> ); }; export default Job;
额外排查点
在App组件的fetch回调中打印返回数据,确认接口返回的是否为直接的200条数组:
useEffect(() => { fetch('http://demo4666569.mockable.io/groups') .then(response => response.json()) .then(res => { console.log('接口返回数据长度:', res.length); // 确认是否为200 setJobs(res); }) .catch(err => setError(err)) }, [])
如果接口返回的是嵌套结构(比如{ data: [...] }),需要修改为setJobs(res.data)来获取正确的数组。
内容的提问来源于stack exchange,提问作者user989988
相关产品推荐
相关产品推荐

