【问题标题】:How to later use a method on a object that is stored in useState?以后如何在 useState 中存储的对象上使用方法?
【发布时间】:2021-10-20 05:29:51
【问题描述】:

我有一个类似这样的自定义钩子:

export const useSomeHook = () => {
    const [provider, setProvider] = useState(null);
        
    useEffect(() => {
        // init stuff using third party library
        setProvider(...);
    }, []);
    
    return [provider];
} 

在应用程序中,我在某处以只读模式使用,但 provider 有我想使用的方法,如下所示:

provider.once(txHash, (transaction) => {
    // Emitted when the transaction has been mined
})

问题是由于useState,它创建了一个只读对象,所以我不能使用提供者的方法。我不能只在钩子中传入数据来初始化这个函数,因为txHash是随着用户交互而变化的东西,并且提供者连接到websocket(初始化时由第三方库发起)

【问题讨论】:

    标签: javascript reactjs react-hooks use-effect use-state


    【解决方案1】:

    我想如果你使用 useRef 而不是 useState 应该可以工作

    export const useSomeHook = () => {
        const providerRef = useRef(null);
            
        useEffect(() => {
            // init stuff using third party library
            providerRef.current = ...
        }, []);
        // you don't need to put it in an array since it's only one item
        return providerRef.current;
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多