Redux-toolkit create action prepare 不会添加 Typescript 的值



我遵循这里的官方示例redux工具包参考,并尝试键入PayloadAction,如下所示:

import {
createSlice,
PayloadAction,
nanoid,
} from '@reduxjs/toolkit'
type MyObjectType = {
uuid: string
anotherProp: string
// ...
}
const slice = createSlice({
name: 'oneSlice',
initialState: {},
reducers: {
addSomething: {
reducer(state, action: PayloadAction<{x: string; anotherProp: string}>) {
const { x, uuid, anotherProp } = action.payload // got an error here on uuid
// do something with { x, uuid, anotherProp }
// I need to use it as index : state.something[uuid] = { uuid: uuid, anotherProp: anotherProps }
},
prepare(x: string, anotherProp: string) {
return {
payload: {
uuid: nanoid(),
x,
anotherProp,
},
}
},
}
}
})

然而,我在尝试销毁action.payload时遇到了一个错误。如何推断action.payloaduuid属性?

我得到了一个奇怪的解决方案,我在PayloadAction中传递整个对象类型,并在prepare()中修改uuid

...
addSomething: {
reducer(state, action: PayloadAction<{x: string; myobject: MyObjectType}>) {
const { x, myobject } = action.payload 
// there is no problem here
},
prepare(x: string, myobject: MyObjectType) {
myobject.uuid = nanoid()
return {
payload: {
x
myobject: myobject
},
}
},
}
...

有更好的方法来解决这个问题吗?

您必须添加它:

reducer(state, action: PayloadAction<{x: string; anotherProp: string; uuid: string}>) {

如果你定义了一些不存在的东西,这仍然会警告你:

reducer(state, action: PayloadAction<{x: string; anotherProp: string; foo: string}>) {

但是仅仅请求一个子类型(就像你所做的那样(并不是一个错误,所以它不会警告你

相关内容

  • 没有找到相关文章

最新更新