我正在构建一个React-Redux应用程序,需要一个可以访问增强存储的中间件功能。我无法在中间件功能中获得可用的增强存储。这是否可行,如果可行,如何实现?
https://codesandbox.io/s/redux-enhanced-store-in-middleware-e1c5uv?file=/src/main.ts
import {createElement} from 'react'
import {Provider, useDispatch} from 'react-redux'
import {configureStore, getDefaultMiddleware} from '@reduxjs/toolkit'
import { createRoot } from 'react-dom/client'
function reducer(state, action){
console.debug("reducer...")
return state
}
const apiMiddleware = (store) => (next) => (action) => {
console.debug("apiMiddleware", store) // I would like store.api here
return next(action)
}
const storeEnhancer = (next) => {
const api = {doSomething: () => console.debug("api.doSomething")}
return (reducer, initialState) => {
const the_store = {api, ...next(reducer, initialState)}
console.debug("storeEnhancer", the_store)
return the_store
}
}
const store: any = configureStore({
reducer,
middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(apiMiddleware),
enhancers: (defaultEnhancers) => [...defaultEnhancers, storeEnhancer],
})
const ClickButton = () => {
const dispatch = useDispatch()
const onClick = () => dispatch({type: "action"})
return createElement("button", {onClick}, "clicky")
}
export const app = () =>
{
const rootElement = document.getElementById("root")
const root = createRoot(rootElement!)
root.render(createElement(Provider, {store, children: createElement(ClickButton)}))
return createElement("div", {}, "hello")
}
1条答案
按热度按时间iszxjhcz1#
中间件不会将 * 整个 * Redux存储作为它们最外层的参数,相反,它们会得到一个 * 部分 * 版本--只有
{dispatch, getState}
。这就是为什么我更喜欢将该变量称为
storeApi
,而不是store
,因为它 * 不是 * 整个商店:因此,如果您的增强器将额外的字段附加到
store
示例,则无法在中间件中访问这些字段。