我正在使用useSubscription
(来自@apollo/react-hooks
库)通过WebSockets订阅表更新,但无法使其与React(nextjs)中的redux模式一起使用。
我正在通过以下方式从index.js(页面)调度操作:
const dispatch = useDispatch()
useEffect(() => {
dispatch(listenForActivities());
}, [dispatch])
和listenForActivities
看起来像这样:
export const listenForActivities = () => {
return dispatch => {
dispatch(listenForActivitiesStarted());
const now = moment().utc().format()
const newActivitiesSubscription = gql`
subscription newActivities($now: timestamp!) {
activities (where: {updated_at: {_gt: $now}}) {
id
type
start_at
end_at
baby_id
text
}
}
`;
const { data, loading } = useSubscription(
newActivitiesSubscription,
{ variables:
{
now
}
}
);
if (data && data.activities) {
dispatch(addActivitySuccess(data.activities[0]))
}
dispatch(listenForActivitiesSuccess())
}
};
我遇到的错误是:
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
See https://fb...me/react-invalid-hook-call for tips about how to debug and fix this problem.
我假设我正在“违反挂钩规则”(也许是因为这是一个长期存在的订阅?),但不确定该走哪条路。
感谢您的帮助!