Reputation: 9680
I have the following code. For some reason when I try to instantiate the Movie objects from inside the getAllMovies static method I get the error. What am I doing wrong?
Movie.js:7 Uncaught TypeError: Cannot set property 'name' of undefined
at new Movie (Movie.js:7)
import React, { Component } from 'react';
class Movie extends Component {
constructor(name, year, genre) {
this.name = name
this.year = year
this.genre = genre
}
static getAllMovies() {
let movies = []
let movie = new Movie("ss","sss","aaa")
/*
for(let index = 1; index <= 10; index++) {
let movie = new Movie(`Movie {index}`,2000 + index,`Genre {index}`)
movies.push(movie)
} */
return movies
}
}
Upvotes: 2
Views: 82
Reputation: 1622
I think your concept about react was wrong.
In react component, props
and state
are used for data management.
So the statement are below:
class Movie extends component{
constructor(props){
super(props);
this.state = {
name : this.props.name,
year : this.props.year,
genre : this.props.genre,
}
}
the above error was occurred because of your constructor
Upvotes: 0
Reputation: 92461
The Movie
class needs to call super()
in it's constructor to have the correct value for this
:
class Component{}
class Movie extends Component {
constructor(name, year, genre) {
super()
this.name = name
this.year = year
this.genre = genre
}
static getAllMovies() {
let movie = new Movie("ss","sss","aaa")
return movie
}
}
console.log(Movie.getAllMovies())
Upvotes: 3