Home > Blockchain >  Typescript array of function components
Typescript array of function components

Time:12-20

Why I could not do: <BookingGetServices numGuests={this.state.numGuests}/>

Here is the code:

constructor()
    {
        super({});

        this.pages = [
            <BookingGetNumGuests submitNumGuests={this.submitNumGuests}/>,
            <BookingGetServices numGuests={this.state.numGuests}/>
        ];

        this.state = {
            pageIndex: 0,
            numGuests: -1
        };
    }
interface DefinedProps
{
    numGuests: number
}

function BookingGetServices(props: DefinedProps)
{
    const {numGuests} = props;

    return (
        <header className={"BookingPage-header"}>
            <h1>{numGuests}</h1>
        </header>
    );
}
BookingApplication.tsx:26 
        
       Uncaught TypeError: Cannot read properties of undefined (reading 'numGuests')
    at new BookingApplication

CodePudding user response:

You are trying to access this.state before it exists

this.state = {
  pageIndex: 0,
  numGuests: -1
};

this.pages = [
  <BookingGetNumGuests submitNumGuests={this.submitNumGuests}/>,
  <BookingGetServices numGuests={this.state.numGuests}/>
];

The fact that it's TypeScript doesn't change anything, because this is a runtime error

  • Related