如何在React with TS中将动作作为变量进行调度



如何将type属性作为参数传递到调度函数中?

type Actions = 
| {type: 'addToBag', bagProducts: string[]}
| {type: "increaseQty", prodName: string}
| {type: "decreaseQty", prodName: string}
interface InitialState {
bagProducts: string[]
}
const reducer = (state: InitialState, action: Actions): InitialState => {
switch (action.type) {
case 'addToBag':
return {
// something
}
case 'increaseQty':
return {
// something
}
case 'decreaseQty':
return {
// something
}
default: 
return state
}
}
const [cartProductsStateR, dispatch] = useReducer(reducer, initialState)

调度功能(实际情况(:

const decreaseProductQty = (name: string) => {
dispatch({type: 'decreaseQty', prodName: name})
}

希望如何:

const decreaseProductQty = (name: string, action: string) => {
dispatch({type: action, prodName: name})
}

但如果我这样做,我会在属性type:上得到这个错误

Type 'string' is not assignable to type '"addToBag" | "increaseQty" | "decreaseQty"'

我试过这个:

const decreaseProductQty = (name: string, action: "addToBag" | "increaseQty" | "decreaseQty") => {
dispatch({type: action, prodName: name})
}

然后我犯了这个错误,但我不明白为什么?

Type '"addToBag" | "increaseQty" | "decreaseQty"' is not assignable to type '"addToBag" | "increaseQty" | "decreaseQty"'

有没有一个wat,我可以接收action作为参数,并将其传递给dispatch,而不是普通字符串?

它给出了错误,因为您的有效载荷是不同类型的。

在下面的情况下,如果动作是";addToBag"?你不能有相同的有效载荷";prodName";在你所有的行动中。这就是TypeScript抱怨的原因。

const decreaseProductQty = (name: string, action: "addToBag" | "increaseQty" | "decreaseQty") => {
dispatch({type: action, prodName: name})
}

我会把你的代码重构成这样的动作创建者:


const addToBag = (bagProducts: string[]) => ({type: 'addToBag', bagProducts} as const)
const increaseQty = (prodName: string) => ({type: 'increaseQty', prodName} as const)
const decreaseQty = (prodName: string) => ({type: 'increaseQty', prodName} as const)

type Actions = 
| ReturnType<typeof addToBag>
| ReturnType<typeof increaseQty>
| ReturnType<typeof decreaseQty>

// later in a component
const decreaseProductQty = (name: string) => {
dispatch(decreaseQty(name))
}

最新更新