Pau*_*ool 0 reactjs next.js apollo-client react-hooks react-custom-hooks
我仍然无法理解 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 ] );
}
Run Code Online (Sandbox Code Playgroud)
定制挂钩
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'
}
]
}
}
} );
}
}
Run Code Online (Sandbox Code Playgroud)
结果错误:
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
Run Code Online (Sandbox Code Playgroud)
始终在 React 函数的顶层使用 Hooks。你应该useSetMetafields在旁边打电话useQuery。为了使您的代码正常工作,您需要更改自定义挂钩的方面。我的建议以及您提供的代码量:
export default function MyComponent() {
const { loading, error, data } = useQuery( GET_ORDERS );
{ doUpdateMetaField } = useSetMetafields();
const setOrdersInMetafields = ( orders: Array<OrderModel> ) => {
// Make doUpdateMetaField function return something if you need and collect it here
doUpdateMetaField( { customerId, value: orders, field: 'duplicateOrders' } );
}
useEffect( () => {
setOrdersInMetafields( orders );
}, [ orders ] );
}
Run Code Online (Sandbox Code Playgroud)
export const useSetMetafields = () => {
[ updateMetafield, { loading, error, data } ] = useMutation( SET_METAFIELD_ON_CUSTOMER );
const doUpdateMetaField = ({ customerId, value, field }, { customerId: string, value: any, field: string } ) => {
updateMetafield( {
variables: {
input: {
id: customerId,
metafields: [
{
namespace: 'app-name',
key: field,
value: JSON.stringify( value ),
type: 'string'
}
]
}
}
} );
}
return {
doUpdateMetaField
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2314 次 |
| 最近记录: |