gpt4 book ai didi

reactjs - TypeScript/React - 映射 av 对象数组

转载 作者:行者123 更新时间:2023-12-05 05:12:29 25 4
gpt4 key购买 nike

我正在尝试映射从 Unsplash 接收到的对象数组应用程序接口(interface)。我读过一些关于 indexers 的内容在 TypeScript 中,但我不确定我是否完全理解它。我有一个无状态的 React 组件,它从父级接收状态的支持。该值是一个对象数组。 (参见来自 unsplash API 的示例)。我如何定义从 API 接收到的对象的形状?

我的代码:

interface IProps {
images: [{}];
}

interface IIMageUrls {
image: {
urls: { regular: string}
}
[index: string]: any;
}

export default class ImageList extends React.Component<IProps, {}> {
constructor(props: IProps) {
super(props);
}

render() {
this.props.images.map((image: IIMageUrls) => {
return <img src={image.urls.regular} />
});
}
}

unsplash JSON 示例:

{      
"results": [
"urls": {
"raw": "https://images.unsplash.com/photo-1416339306562-f3d12fefd36f",
"full": "https://hd.unsplash.com/photo-1416339306562-f3d12fefd36f",
"regular": "https://images.unsplash.com/photo-1416339306562-f3d12fefd36f?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&s=92f3e02f63678acc8416d044e189f515",
"small": "https://images.unsplash.com/photo-1416339306562-f3d12fefd36f?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&s=263af33585f9d32af39d165b000845eb",
"thumb": "https://images.unsplash.com/photo-1416339306562-f3d12fefd36f?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=200&fit=max&s=8aae34cf35df31a592f0bef16e6342ef"
}
]
}

解决方案/最终代码:

interface IImageUrls {
[index: string]: string;
regular: string;
}

interface IImage {
urls: IImageUrls;
}

interface IProps {
images: Array<IImage>;
}

export default class ImageList extends React.Component<IProps, {}> {
constructor(props: IProps) {
super(props);
}

render() {
const images = this.props.images.map((image, index) => {
return <img src={image.urls.regular} key={index} />;
});
return images;
}
}

最佳答案

看起来您正在寻找这样的东西:

interface IImageUrls {
[index: string]: string
}

interface IImage {
urls: IImageUrls;
}

interface IProps {
images: Array<IImage>;
}

IImageurls 属性需要索引签名。

如果您知道 regular 将始终存在,您可以使用:

interface IImageUrls {
[index: string]: string;
regular: string;
}

基本上说这个接口(interface)总是有regular,但可以有其他键。

这取决于您需要如何使用 IImageUrls。如果您只需要 regular,那么您不需要索引签名,只需将其键入:

interface IImageUrls {
regular: string;
}

关于reactjs - TypeScript/React - 映射 av 对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54504177/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com