[英]Typescript error Property x does not exist on type 'Readonly<Props> & Readonly<{ children?: ReactNode; }>'
I am new to Typescript
.我是Typescript
。 Using Nextjs, I have a basic component I would like to typecheck, however I am getting the error.使用 Nextjs,我有一个基本组件要进行类型检查,但是出现错误。 How can i typecheck my array of objects?如何对我的对象数组进行类型检查?
ERROR in C:/Users/Matt/sites/shell/pages/index.tsx(22,4):
22:4 Property 'swc' does not exist on type 'Readonly<Props> & Readonly<{ children?: ReactNode; }>'.
20 | render() {
21 | const {
22 | swc: { results }
| ^
23 | } = this.props;
type Props = {
results: Array<any>;
};
Component:成分:
interface Props {
swc: Object;
results: Array<any>;
}
class swc extends React.Component<Props, {}> {
static async getInitialProps() {
const res = await fetch("https://swapi.co/api/people/");
const swc = await res.json();
return {
swc
};
}
render() {
const {
swc: { results }
} = this.props;
return results.map(swc => (
<Layout>
...
</Layout>
));
}
}
export default swc;
this.props: this.props:
{ swc:
{ count: 87,
next: 'https://swapi.co/api/people/?page=2',
previous: null,
results:
[ [Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object] ] },
url:
{ query: [Getter],
pathname: [Getter],
asPath: [Getter],
back: [Function: back],
push: [Function: push],
pushTo: [Function: pushTo],
replace: [Function: replace],
replaceTo: [Function: replaceTo] } }
You already have the props
object defined inside the swc
class, no need to destruct the class itself.您已经在swc
类中定义了props
对象,无需销毁类本身。
You're essentially trying to access
swc.props.swc.results
when you should be accessingswc.props.results
instead当您应该访问swc.props.swc.results
时,您实际上是在尝试访问swc.props.results
In general though, this seems like an incorrect component set up and I'm confused by your props
definition as you seem to be passing results
prop and then swc
to props, which is the component itself (?)但总的来说,这似乎是一个不正确的组件设置,我对您的props
定义感到困惑,因为您似乎将results
prop 然后swc
传递给 props,这是组件本身(?)
It's hard for me to answer this without further detail, but I'd imagine you'd want to do something like this:如果没有进一步的细节,我很难回答这个问题,但我想你会想要做这样的事情:
import React, { Component } from 'react'
import fetch from 'isomorphic-unfetch'
type Props = {
results: any[], // < try to be more specific than any[]
}
// React Components should per convention start with Uppercase
class Swc extends Component<Props, {}> {
static async getInitialProps(ctx) {
const res = await fetch("https://swapi.co/api/people/")
const json = await res.json()
return { json.swc.results }
}
render() {
const { results } = this.props
// React components should always return a singular tag
// (eg. div, React.Fragment, but not array of <Layout>
const renderResults = results && results.map(result => (
<Layout>
{result}
</Layout>
))
return (
<>
{renderResults}
</>
)
}
}
export default Swc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.