根据@Lesiak 请求进行编辑:
这是我的 getProducts 调用
// @api/shopifyProducts.ts
import Client from 'shopify-buy'
const client = Client.buildClient({
// TODO: add to dotenv
domain: 'some-domain.myshopify.com',
storefrontAccessToken: 'example-token-2597293846729587293875'
})
export const getProducts = async () => {
try {
const data = await client.product.fetchAll()
const products = await data.map((item) => {
return {
title: item.title,
description: item.description
// images: item.images
}
})
return products
} catch (error) {
throw new Error(`Product API fetch failed: ${error}`)
}
}
我还像这样重构了我的组件:
import React, { Component } from 'react'
import { getProducts } from '@api/shopifyProducts'
class TheListProducts extends Component<{}> {
constructor(props) {
super(props)
this.state = {
products: null
}
}
async componentDidMount() {
this.setState({
products: await getProducts()
})
console.log(this.state.products) ==> Error: Property 'products' does not exist on type 'Readonly<{}>'
}
render() {
return <p>Hey</p>
}
}
export default TheListProducts
初始问题:
各位开发者早上好,
我偶然发现了一个即使在网络上进行广泛研究也无法独自解决的问题。由于我是 TS 的新手,所以我发现我并不能 100% 理解到底发生了什么。
我在 React 中有一个组件,我在其中异步从 Shopify 内容中获取内容,并且我想在渲染函数中打印它。
import React, { Component } from 'react'
import { getProducts } from '@api/shopifyProducts'
interface Product {
title: any
description: any
}
interface ListState {
products: {
[key: string]: Product | Function
}
}
class TheListProducts extends Component<{}, ListState> {
async componentDidMount() {
this.setState({
products: await getProducts()
})
}
render() {
return <p>{this.state.products}</p>
}
}
export default TheListProducts
我收到以下错误:
(property) products: {
title: string;
description: string;
}[]
Type '{ title: string; description: string; }[]' is not assignable to type '{ [key: string]: Product; }'.
Index signature is missing in type '{ title: string; description: string; }[]'.ts(2322)
我可以阅读,并且我认为我理解该错误,但不知道该怎么办。
如果有人能用简单的英语向我解释它,那就太棒了。
根据网络研究,我尝试增强产品界面,如下所示:
interface Product {
title: string
description: string
[key: string]: string | number | undefined | Function
}
但这就像盲目地进入......
最佳答案
关于javascript - 类型 'products' 上不存在属性 'Readonly<{}>',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61074901/