我剛剛在ReactJS中出現了新問題,並且遇到了問題。我無法解決它。看起來一切正常,但仍然控制檯讓我:必須返回有效的React元素(或null)。你可能已經返回undefined,一個數組或其他無效的對象
必須返回一個有效的React元素(或null)。你可能有 返回未定義,數組或其他無效的對象。
這裏是我的代碼:
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;
Pokemon.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;
感謝您的幫助!
這是不正確的JSX。 –
我剛剛試圖將括號添加到所有if和else語句中,並且仍存在相同的問題。 – Anna
爲什麼不是真的?我的意思是,我在一個反應項目,這是我如何封裝HTML代碼之前,打印它在返回功能... 如果你不能這樣做: const data =(