使用“eth_requestAccounts”请求 Metamask 在 next.js 中不起作用

stack overflow requesting Metamask with "eth_requestAccounts" does not work in next.js
原文答案

答案:

作者头像

第一的

      <Button
          onClick={() => {
            // this is logging.
            console.log("clicked to send request to Metamask");
            connect;
          }}
        >
          Connect
        </Button>

不能工作,因为你需要做 connect()

      <Button
          onClick={() => {
            // this is logging.
            console.log("clicked to send request to Metamask");
            connect(); // <===
          }}
        >
          Connect
        </Button>

第二个连接可能正在工作,如果已经连接,它将不会打开弹出窗口。尝试这样做。

const connect = () => {
    provider.request({ method: "eth_requestAccounts" })
         .then(response => console.log(response)
         .catch(err => console.log(err)
  };

或者如果你想保持异步

const connect = async () => {
    try {
      const addresses = await provider.request({ method: "eth_requestAccounts" });
      console.log(addresses)
    } catch (e) {
      console.log("error in request", e);
      // location.reload();
    }
  };