我有一个组件,应该从api获取并使用不同的变量名呈现数据。我有两个响应,它们具有相同的数据,但具有不同的变量名称,例如:
FirstReq {
id number
published boolean
publishDate string
newsImage string
newsText string
newsTitle string
}
SecondReq {
anons string
archived boolean
fullText string
id number
postingDate string
title string
}
通常我通过变量名使用它:
interface ItemProps {
item: {
id: number,
title: string,
fullText: string,
anons: string,
postingDate?: string,
image?: string,
},
}
const Item: React.FC<ItemProps> = (props) => {
const { item } = props;
const { id, postingDate, title, anons, image, fullText } = item;
return (
<>
<div>{title}</div>
<div>{postingDate}</div>
<div>{fullText}</div>
</>
)
}
export default Item
但是,如何编写组件以将其与不同的变量名称一起使用?“文本”的变量可以是“ fullText”或“ newsText”或“ articleText”,是否可以在一个通用组件中进行渲染?不知道怎么写。任何人都可以提供帮助或提供建议的方法吗?
IMO最好的解决方案始终是统一从不同的API接收的数据,如果由于某种原因这不可能,并且应该从您的角度进行处理,则有不同的处理方法,我建议作为一种有效的方法是拥有独特的界面,然后映射数据以创建与该界面匹配的模型
例如:
interface ItemInterface {
id: number,
title: string,
postingDate?: string,
...
}
您会得到不同的响应,一个带有postingDate
,另一个带有不同的name publishDate
,因此您可以执行以下操作:
class Item implements ItemInterface {
constructor(itemData) {}
get postingDate() {
return itemData.postingDate || itemData.publishDate;
}
...
...
}
然后在您的组件中,您可以执行以下操作:
const { id, postingDate, title, anons, image, fullText } = new Item(item);
实际上,您可以通过创建一个新的简单对象来实现相同目的,该对象以类似的方式获取值:
const unifiedItem: ItemInterface = {
postingDate: itemData.postingDate || itemData.publishDate
...
}
其他一些建议:
interface ItemPropsInterface {
item: ItemInterface
}
const Item: React.FC<ItemProps> = ({item}) => {
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句