我使用 RTK 查询从服务器加载基本静态的配置,该配置被解析为
Context
并在 Provider
内使用。我可以愉快地使用带有 useConfiguration()
钩子的元素中的配置。
但是,我想在处理操作时使用该配置。
是否可以在reducer中获取
Context
的内容?
当然,我可以将整个配置作为操作负载的一部分传递,但我想避免这样做。原因是配置很大(使序列化动作变大?),这使得在 Storybook 故事中创建动作变得更加困难。
上下文如下:
export const ConfigurationProvider: FC = ({ children }) => {
const { data } = api.useGetConfigurationQuery()
const [state, dispatch] = useReducer(configurationReducer, initialState)
const value = useMemo(
() => ({ configuration: state, dispatch }),
[state, data]
)
useEffect(() => {
if (data) {
dispatch({ type: 'parse', payload: data })
}
}, [data])
return (
<ConfigurationContext.Provider value={value}>
{children}
</ConfigurationContext.Provider>
)
}
这是我要使用配置的地方:
const mySlice = createSlice({
name: 'mySlice',
initialState,
reducers: {},
extraReducers: (builder) => {
builder.addCase(quoteAction.addItem, (state, action) => {
// How can I get the configuration here.
})
},
})
如果切片和 api 是同一存储的一部分(我假设),您可以通过减速器中的状态参数访问 API,如下所示:
extraReducers: (builder) => {
builder.addCase(quoteAction.addItem, (state, action) => {
let config = state.api.getConfiguration.data ?? {}
})
}
但这不是 RTK 查询意义上的订阅。因此,您需要捕获未初始化的 API 或数据过时等情况。