React Redux:更新多个依赖道具的组件

React Redux: Updating Component on Multiple Dependent Props

我有一个 React 组件,我们称它为 Documents。在这个组件中,我需要使用 fetch 加载多条依赖数据。我正在为这些执行数据获取的异步 redux 操作使用 redux thunk。

所以组件看起来像这样:

interface Props {
  comments: Entity[];
  documents: Entity[];
  users: Entity[];
  getComments: Function;
  getDocuments: Function;
  getUsers: Function;
}

export class Documents<Props> {
  public async componentDidMount(props: Props){
    // is this the right lifecycle method for this since
    // it does not really need to change state
    const { documents, users, comments, getDocuments, getUsers, getComments} = props;
    if(!documents || !documents.length){
      await getDocuments();
    } else {
      await getUsers(documents.map(d => d.username));
    }
    getComments(documents, users); // dependent upon both users and documents
  }
  public render() {
    // render documents, users, and comments
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Documents);

这里需要先看一下文档才能加载用户。在我可以加载评论之前,用户和文档都是。在反应中处理这个问题的最佳方法是什么。我的 render 函数将加载负责呈现这些数据的小子组件,但我不希望它们成为连接的组件。

我想我能够通过功能性 component/useEffect 挂钩完成它:

https://codesandbox.io/s/festive-varahamihira-kpssd?file=/src/Documents.js

 useEffect(() => {
    if (!documents || !documents.length) {
      getDocuments();
    } else {
      getUsers(documents);
    }
  }, [documents]);

   useEffect(() => {
    if (users) {
      getComments(documents, users);
    }
  }, [users]);