Pro*_*zak 8 typescript reactjs
我正在从端点获取图像并且无法将每个映射文件推送到我的本地数组中。我收到错误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
Run Code Online (Sandbox Code Playgroud)
重要提示:解决此问题后,我发现我的问题与状态无关。尽管该解决方案允许我将对象推送到数组中,但我直接改变了状态,这在 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] }))
}
Run Code Online (Sandbox Code Playgroud)
Bjö*_*ing 15
你应该mediaLibrary像这样声明你的数组:
state = {
mediaLibrary: Array<{id: string, path: string}>()
}
Run Code Online (Sandbox Code Playgroud)
或者像这样:
state: {
mediaLibrary: {id: string, path: string}[]
} = {
mediaLibrary: []
}
Run Code Online (Sandbox Code Playgroud)
通过第一种方式,您告诉 TypeScript 您想要将具有给定属性的对象放入mediaLibrary数组中。仅使用[]TypeScript 会将never类型放入数组,因此无法将任何内容放入其中。
第二个示例描述了完整的state对象,而不仅仅是包含的数组。
| 归档时间: |
|
| 查看次数: |
21821 次 |
| 最近记录: |