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

时间:2020-10-05 03:13:52

标签: reactjs react-admin

我试图创建类似后台工作程序之类的东西来监视数据库(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);
    ...
}

1 个答案:

答案 0 :(得分:1)

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

此博客将帮助您了解转换的细微之处-> 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 />
}

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

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