我正在从端点获取图像,并且无法将每个映射文件推入本地数组。我收到错误Argument of type 'any' is not assignable to type 'never'
。
blob
都没有成功。function(data)
设置为data: any
,data: {}
,data: File[]
,data: JSON
,并且所有人都说地图功能不适用于这些类型。import * as React from "react"
import { Company } from "data/companies"
import { Asset } from "data/companies"
interface MediaLibraryProps {
company: Company
}
class MediaLibrary extends React.Component<MediaLibraryProps> {
state = {
mediaLibrary: []
}
getMediaLibrary = async () => {
await fetch(
`${process.env.REACT_APP_SA_API_URL}/${this.props.company.id}/medialibrary`,
).then(blob => blob.json())
.then(function (data) {
return data.map((file: Asset) => {
return {
id: file.assetId,
path: file.path
}
})
}).then(data => this.state.mediaLibrary.push(...data))
}
public render() {
const files = this.state.mediaLibrary.map((file: Asset) => (
<div key={file.assetId}>
<div>
<img src={`url(${process.env.REACT_APP_SA_CDN_URL}${file.path})`} />
</div>
</div>
))
return (
<div>
<div>
<h2>Media Library</h2>
{files}
<button onClick={this.getMediaLibrary}>Get Files</button>
</div>
</div>
)
}
}
export default MediaLibrary
重要提示:解决此问题后,我发现我的问题与国家无关。尽管该解决方案允许我将对象推入数组,但我还是直接改变了状态,这是React中的一个nono。见下文:
class MediaLibrary extends React.Component<MediaLibraryProps> {
state = {
mediaLibrary: []
}
getMediaLibrary = async () => {
await fetch(
`${process.env.REACT_APP_SA_API_URL}/${this.props.company.id}/medialibrary`
}
).then(blob => blob.json())
.then(function (data: any) {
return data.map((file: Asset) => Object.assign(file, {
assetId: file.assetId,
path: file.path
}))
}).then((data) => this.setState({ mediaLibrary: [...data] }))
}
答案 0 :(得分:2)
您应该这样声明mediaLibrary
数组:
state = {
mediaLibrary: Array<{id: string, path: string}>()
}
或类似这样:
state: {
mediaLibrary: {id: string, path: string}[]
} = {
mediaLibrary: []
}
使用第一种方法告诉TypeScript,您想将具有给定属性的对象放入mediaLibrary
数组中。仅使用[]
,TypeScript会将never
类型放入数组,因此无法在其中放入任何内容。
第二个示例描述了完整的state
对象,而不仅仅是所包含的数组。