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

Instantiating Objects from Inside the Static Method in JavaScript

我有以下代码。出于某种原因,当我尝试从 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

  }

}

Movie class 需要在其构造函数中调用 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())

我认为你关于反应的概念是错误的。 在 React 组件中,propsstate 用于数据管理。 所以声明如下:

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

以上错误是由于你的构造函数造成的