[英]React: How to update state in an array requiring remote calls for each item?
我是 React 的新手,正在尝试开发一个仪表板类型的应用程序,它有许多“磁贴”,每个磁贴显示一个代表报告指标的值。磁贴定义(标题等)在运行时从单个 JSON 文件中读取. 但是,报告指标值需要每个磁贴 1 次远程 API 调用。 这为用户提供了立即显示的磁贴体验,并在解决时填充报告指标。 我在 React 中对此建模时遇到问题。 这是我到目前为止的简化版本......
// tile info object
export interface ITileData {
title: string;
value: number;
}
// tile component
export interface IDashboardTileProps {
tileData: ITileData;
}
export class DashboardTile extends React.Component<IDashboardTileProps, any> {
public render(): JSX.Element {
return (
<div>{ this.props.tileData.title } = { this.props.tileData.value }</div>
);
}
}
// container component
const TILE_DEFS: ITileData[] = this.getTileDefsFromJson();
export interface ITileContainerState {
tiles: ITileData[];
}
export class TileContainer extends React.Component<any, ITileContainerState> {
constructor() {
super();
this.state = {
tiles: TILE_DEFS
};
}
public componentDidMount() {
// load tile values
this.state.tiles.map((tile, index) => {
// *** THIS IS WHERE I NEED HELP ***
// I need to make an HTTP API call for each tile to get its value
// I don't want to call setState in a loop like this, but I do
// want the values to appear when they are resolved, not all at
// once when all of the HTTP calls are resolved.
});
}
public render(): JSX.Element {
return (
<List
items={ this.state.tiles }
onRenderCell={ tile =>
<DashboardTile tileData={ tile } />
} />
);
}
}
有什么建议?
我以前做过类似的事情,方法是:
this.state.tiles.map
应该返回一个<Tile>
组件的数组,然后您需要创建一个Tile
组件,该组件接收显示和 api 调用所需的所有参数。 父容器所做的只是为它提供进行自己的 api 调用和管理自己的状态所需的道具。
这样做的好处是能够将这些状态更新隔离到该组件,让它呈现加载器/某种“我正在等待返回结果”的每个图块的界面,并且它还将尽快显示数据因为它会返回 api,所以您不必等待所有这些都完成。
伪代码:
this.state.tiles.map((tile, index) => {
return <Tile {...tile} />
}
class Tile extends Component {
constructor() {
super();
this.state = { fetching: true, data: null }
}
componentDidMount() {
// make api calls here
doApi().then((result) => {
this.setState({fetching: false, data: result})
});
}
}
我不熟悉打字稿或您使用的任何东西,所以这只是简单的反应,显然缺少部分,但应该让您大致了解这个想法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.