【问题标题】:ReactJS | Loading State in component doesn't render Spinner反应JS |在组件中加载状态不会呈现 Spinner
【发布时间】:2019-08-06 05:16:17
【问题描述】:

我正在尝试制作一个基于道具和状态显示多个渲染的 React 组件。所以,当我等待承诺得到解决时,我想显示一个微调器组件

主要渲染:

  1. NoResource 组件 => 当用户无效时
  2. Spinner 组件 => 加载所有渲染的时间
  3. BasicRender 组件 => 获取数据但未加载时

下面是我的组件:

/* eslint-disable react/prefer-stateless-function */
import React, { Component, Fragment } from 'react';
import { withRouter } from 'react-router-dom';
import PropTypes from 'prop-types';

import { getUser, listUsers } from '../../config/service';

export class UserDetailsScreen extends Component {
  static propTypes = {
    match: PropTypes.shape({
      isExact: PropTypes.bool,
      params: PropTypes.object,
      path: PropTypes.string,
      url: PropTypes.string
    }),
    // eslint-disable-next-line react/forbid-prop-types
    history: PropTypes.object,
    label: PropTypes.string,
    actualValue: PropTypes.string,
    callBack: PropTypes.func
  };

  state = {
    user: {},
    error: '',
    isloading: false
  };

  componentDidMount() {
    this.fetchUser();
    this.setState({ isLoading: true})
  }

  getUserUsername = () => {
    const { match } = this.props;
    const { params } = match;
    return params.username;
  };

  fetchUser = () => {
    getUser(this.getUserUsername())
      .then(username => {
        this.setState({
          user: username.data,
          isloading: false
        });
      })
      .catch(({ message = 'Could not retrieve data from server.' }) => {
        this.setState({
          user: null,
          error: message,
          isLoading: false
        });
      });
  };

  validateUsername = () =>
    listUsers().then(({ data }) => {
      const { match } = this.props;
      if (data.includes(match.params.username)) {
        return true;
      }
      return false;
    });

  // eslint-disable-next-line no-restricted-globals
  redirectToUsers = async () => {
    const { history } = this.props;
    await history.push('/management/users');
  };

  renderUserDetails() {
    const { user, error } = this.state;
    const { callBack, actualValue, label, match } = this.props;

    return (
      <div className="lenses-container-fluid container-fluid">
        <div className="row">
          .. More Content ..
          {user && <HeaderMenuButton data-test="header-menu-button" />}
        </div>
        {user && this.validateUsername() ? (
          <Fragment>
           .. Content ..
          </Fragment>
        ) : (
          <div className="container-fluid">
            {this.renderNoResourceComponent()}
          </div>
        )}
        <ToolTip id="loggedIn" place="right">
          {user.loggedIn ? <span>Online</span> : <span>Oflline</span>}
        </ToolTip>
      </div>
    );
  }

  renderNoResourceComponent = () => {
    const { match } = this.props;
    return (
      <div className="center-block">
        <NoResource
          icon="exclamation-triangle"
          title="Ooops.."
          primaryBtn="« Back to Users"
          primaryCallback={this.redirectToUsers}
        >
          <h5>404: USER NOT FOUND</h5>
          <p>
            Sorry, but the User with username:
            <strong>{match.params.username}</strong> does not exists
          </p>
        </NoResource>
      </div>
    );
  };

  renderSpinner = () => {
    const { isLoading, error } = this.state;
    if (isLoading && error === null) {
      return <ContentSpinner />;
    }
    return null;
  };

  render() {
    return (
      <div className="container-fluid mt-2">
        {this.renderSpinner()}
        {this.renderUserDetails()}
      </div>
    );
  }
}

export default withRouter(UserDetailsScreen);

问题是: 我得到了微调器和主要组件,我收到了这个错误: Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.。你能告诉我我做错了什么吗?

【问题讨论】:

    标签: javascript reactjs state es6-promise


    【解决方案1】:

    错误是因为您正在运行renderUserDetailsComponent,即使您的 API 调用处于加载状态。您只能在加载状态下渲染微调器

    renderUserDetails() {
        const { user, error, isLoading } = this.state;
        if(isLoading) {
            return null;
        }
        const { callBack, actualValue, label, match } = this.props;
    
        return (
          <div className="lenses-container-fluid container-fluid">
            <div className="row">
              .. More Content ..
              {user && <HeaderMenuButton data-test="header-menu-button" />}
            </div>
            {user && this.validateUsername() ? (
              <Fragment>
               .. Content ..
              </Fragment>
            ) : (
              <div className="container-fluid">
                {this.renderNoResourceComponent()}
              </div>
            )}
            <ToolTip id="loggedIn" place="right">
              {user.loggedIn ? <span>Online</span> : <span>Oflline</span>}
            </ToolTip>
          </div>
        );
      }
    

    【讨论】:

    • 这实际上并没有解决它。我想我在这里做错了什么......用完整的错误更新了描述,但问题仍然存在。 contentSpinner 没有被渲染...
    猜你喜欢
    • 2018-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    • 2017-09-18
    • 2016-02-23
    • 2021-07-10
    相关资源
    最近更新 更多