Redux-toolkit create action prepare 不添加 Typescript 的值
Redux-toolkit create action prepare doesn't add the values for Typescript
我在此处遵循官方示例 redux-toolkit reference 并尝试按以下方式键入 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.payload
的 uuid
属性?
我找到了一个奇怪的解决方案,我在 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}>) {
但只是请求一个子类型(就像你一样)不是错误,所以它不会警告你
我在此处遵循官方示例 redux-toolkit reference 并尝试按以下方式键入 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.payload
的 uuid
属性?
我找到了一个奇怪的解决方案,我在 PayloadAction 中传递了整个对象类型并修改了 prepare()
...
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}>) {
但只是请求一个子类型(就像你一样)不是错误,所以它不会警告你