如何在React中使用API webhook接收通知

15

这是我第一次使用Webhooks工作,我想知道是否可能从Webhooks订阅接收通知。 我正在使用create-react-app进行项目开发,并希望使用github的Webhooks订阅功能,在每次提交到我的github存储库时发送警报。 我该如何处理此项目并需要做什么来测试我的Webhooks订阅?

2个回答

9

希望这个提示有所帮助!让我们开始吧...

我建议使用Web Socket,您的应用程序将在后端监听。

这将防止您为后端创建请求循环。

附加信息...

React仅消耗信息,提供和控制的是后端。

希望这可以帮到您。祝您成功!

class Main extends Component {
    ......
    // instance of websocket connection as a class property
    ws = new WebSocket('ws://localhost:3000/ws')
    componentDidMount() {
        this.ws.onopen = () => {
        // on connecting, do nothing but log it to the console
        console.log('connected')
        }
        this.ws.onmessage = evt => {
        // listen to data sent from the websocket server
        const message = JSON.parse(evt.data)
        this.setState({dataFromServer: message})
        console.log(message)
        }
        this.ws.onclose = () => {
        console.log('disconnected')
        // automatically try to reconnect on connection loss
        }
    }
    render(){
        <ChildComponent websocket={this.ws} />
    }
}

在这个例子中,我使用了一个类组件。利用现代特性的一个小技巧是从函数式组件开始。

1
2023年版本是否有React Hooks可用? - jbuddy_13
这是我的WebSocket功能组件的版本:useEffect(() => { const newSocket = new WebSocket("ws://localhost:8080/ws"); newSocket.onopen = () => console.log('已连接');newSocket.onclose = () => console.log('已断开连接'); newSocket.onerror = (err) => console.log("WebSocket错误"); newSocket.onmessage = (e) => { const msgObj = JSON.parse(e.data); console.log("WebSocket接收到消息对象:", msgObj); ... }; return () => { newSocket.close(); };}, []); - undefined

0
不回答楼主的问题,我只是想提供我的函数式组件版本的websocket来补充上面的答案:https://dev59.com/dVIH5IYBdhLWcg3wAHj2#61789517
useEffect(() => {
    const newSocket = new WebSocket("ws://localhost:8080/ws")
    newSocket.onopen = () => console.log('connected');

    newSocket.onclose = () => console.log('disconnected');

    newSocket.onerror = (err) => console.log("ws error");

    newSocket.onmessage = (e) => {
        const msgObj = JSON.parse(e.data);
        console.log("ws receives msgObj: ", msgObj);
        ...

    return () => {
        newSocket.close();
    };
}, []);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接