这里的目标是减少我的组件中的代码量,如下所示:
import {
increaseProductQuantity as increaseProductQuantityAction,
decreaseProductQuantity as decreaseProductQuantityAction,
} from '~/store/modules/createCampaign/actions'
export default function MyComponent() {
const dispatch = useDispatch()
function increaseSurveyQuantity() {
dispatch(increaseProductQuantityAction('survey'))
}
function decreaseSurveyQuantity() {
dispatch(decreaseProductQuantityAction('survey'))
}
function increaseRewardQuantity() {
dispatch(increaseProductQuantityAction('reward'))
}
function decreaseRewardQuantity() {
dispatch(decreaseProductQuantityAction('reward'))
}
}
我尝试为调度操作的函数创建一个单独的文件,如下所示:
import { useDispatch } from 'react-redux'
import {
increaseProductQuantity as increaseProductQuantityAction,
decreaseProductQuantity as decreaseProductQuantityAction,
} from '~/store/modules/createCampaign/actions'
const dispatch = useDispatch()
export function increaseSurveyQuantity() {
dispatch(increaseProductQuantityAction('survey'))
}
export function decreaseSurveyQuantity() {
dispatch(decreaseProductQuantityAction('survey'))
}
export function increaseRewardQuantity() {
dispatch(increaseProductQuantityAction('reward'))
}
export function decreaseRewardQuantity() {
dispatch(decreaseProductQuantityAction('reward'))
}
在我的组件中,我尝试从上面的文件中导入函数:
import { increaseSurveyQuantity } from '~/helper/sponsorFunctions'
但是我收到此错误:
Error: Invalid hook call. Hooks can only be called inside of the body of a function component
.
完成这项工作的正确方法是什么?
您只能在组件或其他钩子中使用钩子。您可以创建自定义钩子useSurvey
,它将生成函数并返回它们:
import { useMemo } from 'react'
import { useDispatch } from 'react-redux'
import {
increaseProductQuantity as increaseProductQuantityAction,
decreaseProductQuantity as decreaseProductQuantityAction,
} from '~/store/modules/createCampaign/actions'
const useSurvey = () => {
const dispatch = useDispatch()
const actions = useMemo(() => ({
increaseSurveyQuantity() {
dispatch(increaseProductQuantityAction('survey'))
},
decreaseSurveyQuantity() {
dispatch(decreaseProductQuantityAction('survey'))
},
function increaseRewardQuantity() {
dispatch(increaseProductQuantityAction('reward'))
},
decreaseRewardQuantity() {
dispatch(decreaseProductQuantityAction('reward'))
}
}), [dispatch])
return actions
}
export default useSurvey
您可以在组件中使用它们,如下所示:
import useSurvey from '~/helper/useSurvey'
export default function MyComponent() {
const {
increaseSurveyQuantity,
decreaseSurveyQuantity,
increaseRewardQuantity,
decreaseRewardQuantity
} = useSurvey()
return (
// JSX
);
}