Typescript错误属性x在类型'Readonly <Props>和Readonly <{子代?:ReactNode; }>'

时间:2020-02-21 11:05:11

标签: javascript typescript

我是Typescript的新手。使用Nextjs,我有一个基本的组件要进行类型检查,但是却遇到了错误。我该如何对对象数组进行类型检查?

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>;
};

组件:

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:

 { 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] } }

1 个答案:

答案 0 :(得分:0)

您已经在props类中定义了swc对象,无需破坏类本身。

实际上,您应该尝试访问swc.props.swc.results ,而不是访问swc.props.results


尽管如此,总的来说,这似乎是一个错误的组件设置,我对您的props定义感到困惑,因为您似乎正在传递results道具,然后将swc传递给道具,这是组件本身(?)

我很难在没有进一步细节的情况下回答这个问题,但是我想您会想要做这样的事情:

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