未定义组件// React and Webpack

问题描述 投票:0回答:2

我正在构建一个React App,它将从Opendota的api中提取并向我显示英雄。这是我第一次使用API​​。我从头开始构建应用程序,所以我没有使用CRA(create-react-app)。

这是我的App.js

import React from 'react';
import {hot} from "react-hot-loader";
import Heroes from "./components/Heroes"

class App extends Component {
    render() {
        return (
            <Heroes heroes={this.state.heroes} />
        )
    }

    state = {
        heroes: []
    };

    componentDidMount() {
        fetch('https://api.opendota.com/api/heroes')
            .then(res => res.json())
            .then((data) => {
                this.setState({ heroes: data })
            })
            .catch(console.log)
    }
}


export default hot(module)(App);

Heroes.js

import React from 'react'

const Heroes = ({heroes}) => {
    return (
        <div>
            <h1>Hero List</h1>
            {heroes.map((hero) => (
                <div>
                    <div>
                        <h5>{hero.name}</h5>
                        <h6>{hero.id}</h6>

                    </div>
                </div>
            ))}
        </div>
    )
};

export default Heroes

只是在寻找一个可以为我指明正确方向的答案。

javascript reactjs api webpack react-dom
2个回答
1
投票

您尚未从react导入Component。因此,您必须必须从'react'导入Component,这样您的代码将类似于

import React,{Component} from 'react';
import {hot} from "react-hot-loader";
import Heroes from "./components/Heroes"

class App extends Component {
   render() {
      return (
          <Heroes heroes={this.state.heroes} />
      )
   }

   state = {
      heroes: []
   };

   componentDidMount() {
      fetch('https://api.opendota.com/api/heroes')
        .then(res => res.json())
        .then((data) => {
            this.setState({ heroes: data })
        })
        .catch(console.log)
    }
   }


 export default hot(module)(App);

0
投票

React组件的使用方式

import React, {Component} from 'react';
class App extends Component{}

其他方式,如果您不导入,则直接导入

import React from 'react';
class App extends React.Component{}
© www.soinside.com 2019 - 2024. All rights reserved.