在类组件中使用Redux Toolkit查询挂钩

gv8xihay  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(214)

我们有一个非常大的代码库,有271个类组件和旧的redux(不是redux工具包)。
我们正在迁移到redux工具包,并采用RTK-Query作为我们的异步状态管理器。我们将把基于redux-saga的功能迁移到rtk-query,并调整我们的reducer。
对于功能组件,这两件事都很容易做到
1.获取数据,加载状态
1.分派动作以请求该数据。

const {data: posts, isLoading, isError, isSuccess } = usePosts();

但是,如何在基于类的组件中执行此操作...

componentDidMount(){
  //what to dispatch here ?
}

render(){
   const {data: posts, isLoading, isError, isSuccess } = fromWhichPlace;
}
ccrfmcuu

ccrfmcuu1#

我们在文档中专门介绍了这一主题:

根据这些页面,您需要执行以下操作:

const mapState = (
  state: RootState,
  ownProps: RouteComponentProps<{ id: string }>
) => ({
  id: Number(ownProps.match.params.id),
  post: endpoints.getPost.select(Number(ownProps.match.params.id))(state),
  updatePostState: endpoints.updatePost.select(ownProps.match.params.id)(state), // TODO: make selectors work with the requestId of the mutation?
  deletePostState: endpoints.updatePost.select(ownProps.match.params.id)(state)
});

const mapDispatch = {
  getPost: endpoints.getPost.initiate,
  updatePost: endpoints.updatePost.initiate,
  deletePost: endpoints.deletePost.initiate
};

const connector = connect(mapState, mapDispatch);
type PostDetailProps = ConnectedProps<typeof connector> & RouteComponentProps;

export class PostDetailComp extends React.Component<PostDetailProps> {
  state = {
    isEditing: false
  };

  componentDidMount() {
    const { id, getPost } = this.props;
    getPost(id);
  }

  componentDidUpdate(prevProps: PostDetailProps) {
    const { id, getPost } = this.props;
    if (id !== prevProps.id) {
      getPost(id);
    }
  }

  render() {
    const { isEditing } = this.state;
    const {
      // state
      id,
      post: { data: post, isLoading: isPostLoading },
      updatePostState: { isLoading: isUpdateLoading },
      deletePostState: { isLoading: isDeleteLoading },

      // actions
      updatePost,
      deletePost
    } = this.props;

    // snip rendering logic
}

export const PostDetail = connector(PostDetailComp);

但是,**我们 * 强烈 * 建议您将这些组件转换为函数组件,并使用自动生成的查询钩子!**这将 * 更加 * 简单和易于使用,而且钩子有许多内置功能,这些功能很难在类组件中手动复制。

相关问题