我仍然无法将头绕在 Hooks 上。我经常遇到它抱怨我正在做的问题Invalid hook call
。
这一次,是尝试useMutation
在自定义钩子中使用来自 Apollo 的钩子。
如果有人能告诉我我做错了什么,我将不胜感激。
组件(我在哪里调用我的自定义钩子)
export default function MyComponent() {
const { loading, error, data } = useQuery( GET_ORDERS );
const setOrdersInMetafields = ( orders: Array<OrderModel> ) => {
metafieldResp = useSetMetafields( { customerId, value: orders, field: 'duplicateOrders' } );
}
@useEffect( () => {
setOrdersInMetafields( orders );
}, [ orders ] );
}
定制挂钩
export const useSetMetafields( { customerId, value, field }, { customerId: string, value: any, field: string } ) => {
[ updateMetafield, { loading, error, data } ] = useMutation( SET_METAFIELD_ON_CUSTOMER );
useEffect( () => {
onUpdateMetafield();
}, [] );
const onUpdateMetafield = () => {
updateMetafield( {
variables: {
input: {
id: customerId,
metafields: [
{
namespace: 'app-name',
key: field,
value: JSON.stringify( value ),
type: 'string'
}
]
}
}
} );
}
}
结果错误:
Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app