【问题标题】:Why does React fires console.logs 8 times when an event is triggered?为什么 React 在触发事件时会触发 8 次 console.logs?
【发布时间】:2021-07-13 03:00:21
【问题描述】:

我是 React 新手,我不明白为什么我的应用会渲染 2 或 8 次。
我正在使用 window.ethereum 与 MetaMask 进行交互,并在我更改 MetaMask 中的一个帐户时触发一个侦听器。这应该只会触发 console.logs 一次,但它们会被触发 8 次。 如果我删除 useEffect 他们会被解雇 2 次。所有应用都没有其他 useEffects。

useEffect((loading) => {
    let isMounted = true;
    setDarkMode(JSON.parse(localStorage.getItem('isDark')));
    setLoading(true);
    loadBloackchainData(isMounted, loading);
    // cleanup
    return () => (isMounted = false);
  }, []);

  const ethereum = window.ethereum
  ethereum.on('accountsChanged', function (accounts) {
    console.log('is metamask installed?', ethereum.isMetaMask);
    console.log('ethereum.networkVersion : ', ethereum.networkVersion );
    console.log('ethereum.selectedAddress : ', ethereum.selectedAddress );
  });

为什么会被解雇8次?

【问题讨论】:

    标签: reactjs event-handling rendering


    【解决方案1】:

    也许您无意中在每次渲染时添加了一个新的 accountsChanged 处理程序?
    每次渲染时,您可能会添加一个新的处理程序,当帐户信息更改时,您的应用程序可能会调用该处理程序。您可能应该在 useEffect 中订阅/取消订阅该事件:

    useEffect(() => {
      const ethereum = window.ethereum  
      const doAccountThings = (accounts) => {
        // do account stuff
      }
      ethereum.on('accountsChanged', doAccountThings)
      return () => {
        // here unsubscribe from the doAccountThings handler,
        // whatever that syntax is.
      }
    }, [])
    

    useEffect 文档描述了订阅后您可能需要使用此技术进行清理的方式和原因:https://reactjs.org/docs/hooks-effect.html#example-using-hooks-1

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-05
      • 1970-01-01
      • 1970-01-01
      • 2011-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多