React不会根据状态更改重新呈现

时间:2020-10-06 17:36:39

标签: reactjs state rendering react-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);

1 个答案:

答案 0 :(得分: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

上看到更多内容