微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无效的挂接调用挂钩只能在功能组件的内部调用

如何解决无效的挂接调用挂钩只能在功能组件的内部调用

我试图创建类似后台工作程序之类的东西来监视数据库(RabbitMQ)。如果有新条目,它将在用户界面中通知用户

我从应用栏中称我的“后台工作者”:

<AppBar>
    <BGWorker />
</AppBar>

这是我的 BGWorker.js

import { Notify } from 'Notify.ts';

const { Client } = require('@stomp/stompjs');

class BGWorker extends Component {
    componentDidMount(){
        this.client = new Client();
        this.client.configure({
            brokerURL: 'ws://192.168.1.5:15555/ws',connectHeaders:{
                login: "guest",passcode: "guest"
            },onConnect: () => {
                this.client.suscribe('exchange/logs',message => {
                    console.log(message.body);       //yes this does print out correctly
                    Notify(message.body,'info');    //error here
            },});

        this.client.activate();
    }

    render(){
        return (
            <div/>
        );
    }
}

export default BGWorker

这是我的通知功能,位于 Notify.ts

import { usedispatch } from 'react-redux';
import { showNotification } from 'react-admin';

export const Notify = (msg:string,type:string='info') => {
    const dispatch = usedispatch();

    return () => {
        dispatch(showNotification(msg,type)); //this will call react-admin's showNotification function
        //... and other stuff
    };
};

但是我收到一个无效的钩子调用。只能在功能部件的内部调用钩子。”。如何解决此问题?我阅读了react文档并尝试使用自定义钩子,但是它不能正常工作(不确定我是否做对了):

function useFoo(client){ 
    if(client !== undefined)
    {
        client.suscribe('exchange/logs',message => { //I get an 'Uncaught (in promise) TypeError: Cannot read property of 'subscribe' of undefined
            Notify(message.body,'info');
        },}
}

class BGWorker extends Component {
    ...
    onConnect: useFoo(this.client);
    ...
}

解决方法

为了使用钩子,您应该将类​​转换为功能组件。 我假设您对钩子和功能组件一无所知。

此博客将帮助您了解转换的细微之处-> https://nimblewebdeveloper.com/blog/convert-react-class-to-function-component

第二,您需要知道钩子如何工作。引用此-> https://reactjs.org/docs/hooks-intro.html

function BGWorker() {
  const dispatch = useDispatch();

  React.useEffect(() => {
       const client = new Client();
       client.configure({
            brokerURL: 'ws://192.168.1.5:15555/ws',connectHeaders:{
                login: "guest",passcode: "guest"
            },onConnect: () => {
                client.suscribe('exchange/logs',message => {
                    // dispatch your actions here
                    dispatch()
            }),});

        client.activate();
  },[]);

  return <div />
}

最好阅读一些博客,看一些教程,并了解钩子和功能组件。然后尝试解决您的问题。

您可能会在这里找到答案,从长远来看,您需要了解这两个方面。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。