【问题标题】:React is not re-rendering on state changeReact 不会在状态更改时重新渲染
【发布时间】:2020-10-06 17:36:39
【问题描述】:

我正在从 props 接收数据,我必须等到收到数据才能对其进行切片。同时,我想在加载时显示一个圆形进度条,直到加载状态设置为 false 并重新渲染。

但是,现在它卡在加载中并且 componentWillReceiveProps() 不会触发,除非我手动刷新页面?为什么?

import React, { Component } from "react";
import { connect } from "react-redux";
import MemberSync from "./MemberSync";
import CircularProgress from "@material-ui/core/CircularProgress";

interface IProps {
  orgUsers: object;
}
interface IState {
  loading: boolean;
}

class MemberSyncContainer extends Component<IProps, IState> {
  constructor(props: any) {
    super(props);
    this.state = {
      loading: true,
    };
  }

  componentWillReceiveProps() {
    this.setState({ loading: false });
  }

  render() {
    let orgUsers = this.props.orgUsers;
    if (this.state.loading) return <CircularProgress />;
    let usersArray = Object.values(orgUsers).slice(0, -1);
    return <MemberSync usersArray={usersArray} />;
  }
}

const mapStateToProps = (state: any) => {
  return {
    orgUsers: state.orgusers,
  };
};
export default connect(mapStateToProps)(MemberSyncContainer);

【问题讨论】:

    标签: reactjs state rendering react-props


    【解决方案1】:

    你应该避免componentWillReceiveProps。它已被设置为不安全,他们说这通常会导致错误和不一致。
    https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops

    您可能应该使用componentDidUpdate 检查道具是否已更改。这应该可以解决问题。

    componentDidUpdate(prevProps) {
      if (this.props !== prevProps) {
        this.setState({ loading: false });
      }
    }
    

    您可以在https://reactjs.org/docs/react-component.html#componentdidupdate查看更多信息

    【讨论】:

      猜你喜欢
      • 2018-11-29
      • 2020-10-03
      • 2021-11-24
      • 1970-01-01
      • 2018-03-17
      • 1970-01-01
      • 2019-02-27
      相关资源
      最近更新 更多