0

我知道这是一个常见问题,但我陷入了这种情况,我想我知道我的角色是一个对象,它需要是一个数组才能正常工作,.map但我不知道出了什么问题,如果你们可以帮帮我会很棒的。

import React, { Component } from 'react';
import './App.css';

class Card extends Component {
  render() {
    return(
      <div class="ficha">
        <h1>{this.props.name}</h1>
        <h2>{this.props.species}</h2>
        <img src={this.props.image}></img>
      </div>
    );
  }
}

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      characters : []

    }
  }

  componentDidMount() {
    var self = this;
    fetch("characters.json")
       .then(function(response) {
         return response.json();
    })
       .then(function(myJson) {
         self.setState({characters: myJson})


    });

  }
  render() {
  return (
    <div>
      { this.state.characters.map((ch, i) => 
      <Card key={i} name={ch.name} species={ch.species} image={ch.image}/>
     )}
    </div>
  );

      } 
    }



export default App;

这是我有史以来的第一篇文章,我对 React 还很陌生,请放轻松:D 在此先感谢。

4

1 回答 1

0

您应该使用 fat-arrow 函数以便this正确推断,而不是使用 var 来存储this引用:

 componentDidMount() {
    fetch("characters.json")
       .then(response => response.json())
       .then(myJson => {this.setState({characters: myJson})})
    });

现在只要myJson实际上是正确的 json,它应该可以工作。

于 2020-03-14T12:11:39.610 回答