我正在进行一个生成chrome扩展的项目。我正在尝试在popup.tsx中调度函数。但是没有调度。我的商店不更新。同样的代码也适用于后台页面。我能做什么?可能是什么问题?
这是我的popup.tsx:
useEffect(() => {
if (
!ip4Cache.hasOwnProperty(hostname) ||
!geoIPcache.hasOwnProperty(hostname)
) {
console.log('cachede yok')
checkLookup([hostname]).then((res) => {
setIp4(res.data['ip4'][hostname])
dispatch(addIP4(res.data.ip4)) //I also tried store.dispatch in here
})
}
}, [hostname])
这是我的商店:
let sagaMiddleware = createSagaMiddleware()
const localStorage = createLocalStorage()
const persistConfig = {
key: 'root',
storage: localStorage,
}
const reducers = combineReducers({
ip4: ip4Reducer,
})
export type RootState = ReturnType<typeof reducers>
const createPersistReducer = (config) => persistReducer(config, reducers)
export const store = configureStore({
reducer: createPersistReducer(persistConfig),
middleware: [sagaMiddleware],
})
export const persistor = persistStore(store)
sagaMiddleware.run(rootSaga)
wrapStore(store, { portName: 'bla' })
最后一个,IP4切片:
import { createSlice } from '@reduxjs/toolkit'
export const ip4Slice = createSlice({
name: 'ip4',
initialState: {},
reducers: {
addIP4: (state, action) =>
(state = new Object({ ...state, ...action.payload })),
},
})
export const { addIP4 } = ip4Slice.actions
export default ip4Slice.reducer
reducers: {
addIP4: (state, action) => {
// either:
Object.assign(state, action.payload);
// or
return { ...state, ...action.payload }
}
},
请阅读带有Immer的Writing Reducers文档页面,尤其是重置和替换状态。
引用最重要的部分:
一个常见的错误是尝试直接分配
state = someValue
。这行不通!这只会将局部状态变量指向不同的引用。这既不是改变内存中现有的状态对象/数组,也不是返回一个全新的值,因此Immer不会进行任何实际更改。