如何在 React 类组件中获取 RTK 查询 API 端点状态(正在加载、错误等)?

sga*_*dev 1 javascript reactjs redux redux-toolkit rtk-query

好的,我想我已经浏览了几乎所有 RTK Query 的文档,并阅读了 RTK Query 的缓存。看起来它是其中相当大的一部分,即使它目前不是我需要的。

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

从查看文档中有关在类上使用 RTK 查询的示例来看,我似乎在调用中缺少“缓存键” .select(<cache_key>)(state)。但是,我还没有在我的端点中合并标签(我相信我还不需要它们)。

我的问题:

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

代码:

// 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' }
      }),
    }),
  }),
})
Run Code Online (Sandbox Code Playgroud)

mar*_*son 5

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

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

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

const itemAREsults = selectSomeItemA(state);
const itemBResults = selectSomeItemB(state);
Run Code Online (Sandbox Code Playgroud)

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

  • @nadiTime :任何可以访问整个 Redux 根状态的地方:`useSelector` 钩子、`connect` 中的 `mapStateToProps`、使用 `getState()` 的 thunk、使用 `yield select(selector)` 的 saga 等。请参阅 https://redux.js.org/usage/deriving-data-selectors 。 (3认同)