首页 > 解决方案 > 在类组件中使用 setState 时,渲染没有返回任何内容

问题描述

使用 onLoad 事件加载图像后尝试更新状态时,我似乎收到此错误消息。我在班上有一份退货声明,尽管它抱怨我没有。我在运行时收到此消息:

'错误:HPSpotlight(...):渲染没有返回任何内容。这通常意味着缺少 return 语句。或者,不渲染任何内容,返回 null。

   import React, { PureComponent } from 'react';
import { inject, observer } from 'mobx-react';
import {
  HPSpotlightWrapper,
  HPSpotlightImage,
  HPSpotlightBox,
  HPSpotlightContainer,
  HPSpotlightImageContainer,
  HPSpotlightHeaderContainer
} from './index';
import getImagePath from '../../../lib/helpers/shared-helpers/image/get-image-path';
import getImageServerSrc from '../../../lib/helpers/shared-helpers/image/get-image-server-src';
import { UIHeaderNav } from '../../layout/header-nav/header-nav';
import { homepageKGID, sizes } from '../../../lib/constants';

@inject('homePageStore', 'uiStore', 'userStore')
@observer
export class HPSpotlight extends PureComponent {
  render() {
    const { homePageStore, uiStore, userStore, isHomePage, newNav } = this.props;
    const { user, isAnonymous } = userStore.state;
    const { spotlightImageSrc } = homePageStore.state;
    const { screenSize } = uiStore.state;

    let imageSrc = spotlightImageSrc ? spotlightImageSrc.url : null;
    const imagePath = imageSrc && getImagePath(imageSrc);
    const belowTablet = screenSize.width > sizes.tablet;
    this.state = {
      imageLoaded: false
    };
    const headerNavProps = {
      locationKGID: homepageKGID,
      noSearch: belowTablet,
      noCurrency: true,
      user,
      isAnonymous,
      isHomePage,
      newNav
    };

    imageSrc =
      imagePath &&
      getImageServerSrc({
        imagePath,
        layoutWidth: screenSize.width
      });

    return ( 
      <>
        <HPSpotlightContainer>
          <HPSpotlightHeaderContainer>
            <UIHeaderNav {...headerNavProps} />
          </HPSpotlightHeaderContainer>

          <HPSpotlightImageContainer>
            <HPSpotlightWrapper>
              <HPSpotlightImage imageLoaded={this.state.imageLoaded} imageSrc={imageSrc}>
                <img onLoad={() => this.setState({ loaded: true })} src={imageSrc} />
              </HPSpotlightImage>
              <HPSpotlightBox imageSrc={imageSrc} />
            </HPSpotlightWrapper>
          </HPSpotlightImageContainer>
        </HPSpotlightContainer>
      </>
    );
  }
}

它与这条线有关,特别是因为删除它一切运行良好。

<img onLoad={() => this.setState({ loaded: true })} src={imageSrc} />

标签: javascriptreactjssetstate

解决方案


推荐阅读