必须返回有效的React元素(或null)您可能返回了undefined,数组或其他无效对象

【字号: 日期:2024-04-18浏览:31作者:雯心
(adsbygoogle = window.adsbygoogle || []).push({}); 如何解决必须返回有效的React元素(或null)您可能返回了undefined,数组或其他无效对象?

问题是您有多个语句render,因此需要将其括在内部。()请参见以下代码片段。另外,(必须与return其他项目在同一行上,否则它将被视为return仅基本不返回任何内容的行。

class Pokemon extends React.Component { render() { var content = <div></div> return ( <div className='pokemon--spacies'><div className='pokemon--spacies--container'> <div className='pokemon--spacies--sprite'> {content} </div> <div className='pokemon--spacies--name'> Hello</div></div> </div> ) }}ReactDOM.render(<Pokemon/>, document.getElementById(’app’));<script src='https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js'></script><script src='https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js'></script><div id='app'></div>解决方法

我只是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;

宠物小精灵

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;

感谢帮助!

相关文章: