如何在 React Class 组件中获取 RTK 查询 API 端点状态isLoading、错误等?

问题描述

好的,我想我已经阅读了几乎所有 RTK Query 的文档,并阅读了 RTK Query 的缓存。似乎它占了很大一部分,即使我目前不需要它。

因此,我尝试在基于类的组件中使用 RKT 查询进行简单查询,然后从 Redux Store 中选择端点调用的 isLoading 状态。但是,目前在我的 render() {}LoginPage.jsx 中,endpoint.<name>.select()(state)mapStatetoProps 上的 LoginPageContainer.jsx 调用似乎不起作用。 (见下面的代码)。

using RTK Query on classes 上的文档中查看示例,我似乎在 .select(<cache_key>)(state) 调用中缺少一个“缓存键”。但是,我还没有在端点中加入标签(我相信我还不需要它们)。

我的问题:

有人可以阐明在 React Hooks 之外使用的 RTK 查询生成端点的 select() 方法的正确用法吗?我了解用于自动重新获取的缓存标签背后的想法(但这不太可能是这里出了什么问题),但我不确定我在这里缺少的缓存键是如何或只是获取正在运行的端点查询状态的类组件.谢谢大家!

代码

// LoginPage.jsx
import React,{ Component } from 'react'
import PT from 'prop-types'
import LoginForm from './components/LoginForm'

export default class LoginPage extends Component {
  static propTypes = {
    loginWithUsername: PT.func.isrequired,loginWithUsernameState: PT.object.isrequired
  }

  render() {
    // This value never updates
    const { isLoading } = this.props.loginWithUsernameState
    // always outputs "{"status":"uninitialized","isUninitialized":true,"isLoading":false,"isSuccess":false,"isError":false}"
    // Even during and after running the `loginWithUsername` endpoint query
    console.log(this.props.loginWithUsernameState)
    return (
      <div>
        {isLoading && 'Loading ...'}
        <LoginForm
          onSubmit={(values) => this.props.loginWithUsername(values)} />
      </div>
    )
  }
}

// LoginPageContainer.jsx
import { connect } from 'react-redux'
import { teacherApi } from './api'
import LoginPage from './LoginPage'

const { loginWithUsername } = teacherApi.endpoints

const mapStatetoProps = (state) => ({
  loginWithUsernameState: loginWithUsername.select()(state)
})
const mapdispatchToProps = (dispatch) => ({
  loginWithUsername: (payload) => dispatch(loginWithUsername.initiate(payload))
})

export default connect(mapStatetoProps,mapdispatchToProps)(LoginPage)

// api.js
import { createApi,fetchBaseQuery } from '@reduxjs/toolkit/query/react'

export const teacherApi = createApi({
  reducerPath: 'teacherApi',baseQuery: fetchBaseQuery({ baseUrl: '/teacher/' }),endpoints: (builder) => ({
    loginWithUsername: builder.query({
      query: (data) => ({
        url: 'login',method: 'post',body: data,headers: { 'Content-Type': 'application/json' }
      }),}),})

解决方法

传递给 endpoint.select() 的“缓存键”与您传递给钩子的变量相同:

useGetSomeItemQuery("a")
useGetSomeItemQuery("b)"

const selectSomeItemA = endpoint.select("a")
const selectSomeItemB = endpoint.select("b")

const itemAREsults = selectSomeItemA(state)
const itemBResults = selectSomeItemB(state)

这会导致查找 state => state[apiSlice.reducerPath].queries["getSomeItem('a')"] 或该项目的确切缓存数据字段。