从JavaScript中的静态方法内部实例化对象

时间:2018-11-25 21:52:31

标签: javascript reactjs

我有以下代码。由于某些原因,当我尝试从getAllMovies静态方法内部实例化Movie对象时,出现错误。我究竟做错了什么?

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

  }

}

2 个答案:

答案 0 :(得分:2)

Movie类需要在其构造函数中调用super(),以具有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())

答案 1 :(得分:0)

我认为您关于反应的概念是错误的。 在react组件中,propsstate用于数据管理。 因此,声明如下:

class Movie extends component{
     constructor(props){
          super(props);
          this.state = {
               name : this.props.name,
               year : this.props.year,
               genre : this.props.genre,
          }
     }

发生上述错误是由于您的构造函数