我是 ReactJS 的新手,我遇到了问题。我解决不了 似乎一切都很好,但控制台仍然让我:
必须返回有效的 React 元素(或 null)。您可能返回了 undefined、数组或其他一些无效对象。
这是我的代码:
import React from 'react';
import ReactDOM from 'react-dom';
import fetch from 'isomorphic-fetch';
import Pokemon from './Pokemon';
class PokemonList extends React.Component {
constructor(props) {
super(props);
this.state = {
species: [],
fetched: false,
loading: false,
};
}
componentWillMount(){
this.setState({
loading : true
});
fetch('http://pokeapi.co/api/v2/pokemon?limit=151').then(res => res.json())
.then(res =>{
this.setState({
species : res.results,
loading : true,
fetched : true
});
});
}
render() {
const {fetched, loading, species} = this.state;
let content;
//This if seems to be the problem
if(fetched){
content =
<div className="pokemon--species--list">
{species.map((pokemon,index) => <Pokemon key={pokemon.name} id={index+1} pokemon={pokemon}/>)}
</div>;
}
else if(loading && !fetched){
content = <p> Loading ...</p>;
}
else{
content = <div/>;
}
return (
<div>
{content}
</div>
);
}
}
export default PokemonList;
精灵宝可梦.js
import React from 'react';
import ReactDOM from 'react-dom';
class Pokemon extends React.Component {
render() {
const {pokemon, id} = this.props;
return
<div className="pokemon--spacies">
<div className="pokemon--spacies--container">
<div className="pokemon--spacies--sprite">
<img src={`/public/sprites/${id}.png`} />
</div>
<div className="pokemon--spacies--name"> {pokemon.name }</div>
</div>
</div>;
}
}
export default Pokemon;
感谢帮助!