我已经成功实现了一个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
钩子,我得到正确的数据。但是当我使用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 :)
不知道到底发生了什么