gpt4 book ai didi

reactjs - 如何将 createEntityAdapter 应用于 createApi 切片

转载 作者:行者123 更新时间:2023-12-05 04:29:47 24 4
gpt4 key购买 nike

我已经成功地实现了一个 redux-toolkit api。现在,我正在尝试使用 createEntityAdapter 来使用预构建的选择器方法。

import {
createEntityAdapter,
createSelector,
} from '@reduxjs/toolkit'
import api from '@app/redux/reducers/api'

const environmentsAdapter = createEntityAdapter()
const initialState = environmentsAdapter.getInitialState()

export const extendedApiSlice = api.injectEndpoints({
endpoints: (builder) => ({
getEnvironments: builder.query({
query: ROUTES.ENVIRONMENTS,
// IMPORTANT
transformResponse: (responseData: any) => {
return environmentsAdapter.setAll(environmentsAdapter.getInitialState(), responseData)
},
}),
}),
})

// Default api slice hooks
export const {
useGetEnvironmentsQuery, // data returns the normalized data correctly
usePostEnvironmentMutation
} = extendedApiSlice

export const selectEnvironmentsResult = extendedApiSlice.endpoints.getEnvironments.select()

const selectEnvironmentResultData = createSelector(
selectEnvironmentsResult,
environmentResult => {
console.log(environmentResult) // {status: "uninitialized", isUninitialized: true, isLoading: false, isSuccess: false, isError: false}
return environmentResult?.data ?? []
}
)

export const {
selectAll: selectAllEnvironments, // returns an empty array, ERROR!
} = environmentsAdapter.getSelectors(state => {
console.log( state ) // Here the entire redux state is printed, ERROR?
return selectEnvironmentResultData(state) ?? initialState
})

当使用 useGetEnvironmentsQuery Hook 时,我可以正确获取数据。但是当我使用 selectAllEnvironments 时,我得到一个空数组。为什么?

最佳答案

更改 useGetEnvironmentsQuery 的参数即可解决问题。我替换了:

  const { isLoading, isFetching, error } = useGetEnvironmentsQuery({}) // WITH EMPTY OBJECT
const data = useSelector(selectAllEnvironments)
console.log( data ) // empty array

到:

  const { isLoading, isFetching, error } = useGetEnvironmentsQuery() // WITH NO ARGS
const data = useSelector(selectAllEnvironments)
console.log( data ) // data is defined here finally :)

不确定到底发生了什么

关于reactjs - 如何将 createEntityAdapter 应用于 createApi 切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72225616/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com