【问题标题】:How to store and share one single Pusher instance如何存储和共享一个 Pusher 实例
【发布时间】:2021-04-25 17:06:03
【问题描述】:

我了解到不建议使用多个 Pusher 实例,因此我使用 React 的上下文功能。

import React, { useContext, useEffect, useRef } from "react";
import Pusher from "pusher-js";

const PusherContext = React.createContext<Pusher | undefined>(undefined);
export const usePusher = () => useContext(PusherContext)

export const PusherProvider: React.FC = (props) => {
    const clientRef = useRef<Pusher>();

    useEffect(() => {
        if (!clientRef.current) {
            clientRef.current = new Pusher('pusher_key', {
                cluster: 'pusher_cluster',
                authEndpoint: 'auth_endpoint',
            })
        }
    }, [clientRef]);

    return (
        <PusherContext.Provider value={clientRef?.current}>
            {props.children}
        </PusherContext.Provider>
    )
}

我们的 pusher 实例的类型是 Pusherundefined。当我们调用usePusher 时,它始终是未定义的。

import { usePusher } from "./services/pusher";


const Chat: React.FC = (props) => {
    const pusher = usePusher()
    
    useEffect(() => {
        if (pusher) {
            console.log("pusher is initialized/defined")
        } else {
            // it is always undefined
            console.log("pusher is not initialized/defined")
        }
    }, [pusher])

    return (
        <div>
            Test component
        </div>
    )
}

问题出在哪里?

【问题讨论】:

  • 可以使用 React Context reactjs.org/docs/context.html Context is designed to share data that can be considered “global” for a tree of React components
  • 我做到了,但我有一个问题,如果我能得到一些帮助来解决它会很棒。
  • 这个叫做object的语法是什么?.element?

标签: reactjs pusher pusher-js


【解决方案1】:

它似乎工作。包装提供程序时,我只是做错了什么。希望对遇到类似问题的人有所帮助!

【讨论】:

    猜你喜欢
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-04
    • 2013-06-29
    • 2015-08-02
    相关资源
    最近更新 更多