首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >什么是React中的无用构造函数?

什么是React中的无用构造函数?
EN

Stack Overflow用户
提问于 2020-08-27 12:35:16
回答 1查看 2.7K关注 0票数 0

我有两个文件

代码语言:javascript
复制
Description.js and
subjects.js

Subject.js文件包含主题数组

代码语言:javascript
复制
export const Subjects=[
{
    id:1,
    title:"Mathematics",
    text:"Cheat Sheet for Mathematics",
    img:"./Images/math.jpg",
},
{
    id:2,
    title:"C-programming",
    text:"Cheat Sheet for C-Programming",
    img:"./Images/cprog.jpg",
},
{
    id:3,
    title:"Physics",
    text:"Cheat Sheet for Physics",
    img:"./Images/physics.jpg",
},
{
    id:4,
    title:"Youtube",
    text:"Recomended Youtube videos for Learning",
    img:"./Images/youtube.jpg",
  },

  ]

我想在Description.js中使用这个数组。我正在使用一个映射函数

代码语言:javascript
复制
import React, { Component } from 'react';
import {Subjects} from './subjects'

class Description extends Component{
constructor(props){
    super(props);
}
render(){
    const description =this.props.Subjects.map((subjects)=>{
    return(
    <h1>{subjects.title}</h1>
    )
    })
return(
    {description}
    )
   }
  }
    export default Description;

但是我收到了一个错误

代码语言:javascript
复制
TypeError: Cannot read property 'map' of undefined

同样在我的vs代码终端中,我提到了以下内容

代码语言:javascript
复制
Line 2:9:  'Subjects' is defined but never used  no-unused-vars        
Line 5:5:  Useless constructor                   no-useless-constructor
EN

回答 1

Stack Overflow用户

发布于 2020-08-27 12:38:13

“无用的构造函数”是林特警告你可以安全地从代码中删除的构造函数,因为它不会完成任何事情-如果你只有一个super调用(使用创建类时使用的相同参数),构造函数不会做任何有用的事情,因为如果没有给定constructor,类已经自动调用了super

代码语言:javascript
复制
class Parent {
  constructor(name) {
    console.log('parent constructor running', name);
  }
}
class Child extends Parent {}

const c = new Child('bob');

因此,linter告诉您删除以下行:

代码语言:javascript
复制
constructor(props){
    super(props);
}

由于Subjects标识符并未在任何地方使用,因此也可以将其删除。删除该行:

代码语言:javascript
复制
import {Subjects} from './subjects'
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63609257

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档