React 不会在状态更改时重新渲染

React is not re-rendering on state change

我正在从 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);

你应该避免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

查看更多内容