新聞中心
1. 創(chuàng)建 React 應用
要使用 TypeScript 啟動一個新的 Create React App 項目,您可以運行:

成都創(chuàng)新互聯(lián)專注于中大型企業(yè)的成都做網(wǎng)站、網(wǎng)站制作和網(wǎng)站改版、網(wǎng)站營銷服務,追求商業(yè)策劃與數(shù)據(jù)分析、創(chuàng)意藝術與技術開發(fā)的融合,累計客戶成百上千,服務滿意度達97%。幫助廣大客戶順利對接上互聯(lián)網(wǎng)浪潮,準確優(yōu)選出符合自己需要的互聯(lián)網(wǎng)運用,我們將一直專注品牌網(wǎng)站設計和互聯(lián)網(wǎng)程序開發(fā),在前進的路上,與客戶一起成長!
- npx
npx create-react-app my-app --template typescript- yarn
yarn create react-app my-app --template typescript2.安裝SDK
確保將 react、react-dom 和Moralis 安裝為依賴項。然后安裝 react-moralis:
- npm
npm install moralis-v1 react-moralis- yarn
yarn add moralis-v1 react-moralis3.初始化SDK
您將看到以下代碼:
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
ReactDOM.render(
,
document.getElementById("root")
);在您的項目中導入 Moralis Provider 并添加
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { MoralisProvider } from "react-moralis";
ReactDOM.render(
,
document.getElementById("root")
);您可以從 Moralis Dashboard 獲取服務器 (dapp) URL 和 APP ID。轉到您的 Moralis 儀表板,然后單擊服務器名稱旁邊的查看詳細信息。
單擊服務器名稱下方的設置。
4. 驗證用戶
現(xiàn)在 SDK 已成功連接,我們可以使用 Moralis 的強大功能。讓我們登錄一個用戶并立即從您的 Moralis 數(shù)據(jù)庫中的所有鏈獲取他們的所有代幣、交易和 NFT。
在 App.tsx 中調(diào)用應用程序內(nèi)的 useMoralis 鉤子,輸入以下代碼:
import React, { useEffect } from 'react';
import logo from './logo.svg';
import './App.css';
import { useMoralis } from "react-moralis";
function App() {
const { authenticate, isAuthenticated, isAuthenticating, user, account, logout } = useMoralis();
useEffect(() => {
if (isAuthenticated) {
// add your logic here
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isAuthenticated]);
const login = async () => {
if (!isAuthenticated) {
await authenticate({signingMessage: "Log in using Moralis" })
.then(function (user) {
console.log("logged in user:", user);
console.log(user!.get("ethAddress"));
})
.catch(function (error) {
console.log(error);
});
}
}
const logOut = async () => {
await logout();
console.log("logged out");
}
return (
Moralis Hello World!
);
}
export default App;5.從localhost查看頁面
在 package.json 所在的項目目錄中使用以下命令在 localhost 上運行您的應用程序
- npm
npm start
- yarn
yarn start6. 使用 Metamask 登錄
訪問網(wǎng)頁并單擊登錄。您的 Metamask 將彈出并要求您登錄。
7. 查看 Moralis 數(shù)據(jù)庫中的所有用戶資產(chǎn)
一旦用戶登錄 Moralis,就會從所有鏈中獲取有關該用戶的所有鏈上數(shù)據(jù),并將其放入 Moralis 數(shù)據(jù)庫。要查看 Moralis 數(shù)據(jù)庫,請轉到您的服務器并單擊儀表板。
單擊儀表板后,您將看到該服務器的數(shù)據(jù)庫。 Moralis 從用戶地址處于活動狀態(tài)的所有區(qū)塊鏈中獲取數(shù)據(jù),您可以在一個數(shù)據(jù)庫中查看和查詢用戶的所有代幣、NFT 和過去的交易。
Moralis 數(shù)據(jù)庫從所有鏈中獲取所有用戶數(shù)據(jù)并實時更新,以防用戶在鏈上移動資產(chǎn)。
移動資產(chǎn)
嘗試移動 Metamask 錢包中的資產(chǎn),并觀察 Moralis 數(shù)據(jù)庫如何實時更新記錄。
當前標題:創(chuàng)新互聯(lián)Moralis教程:Moralis與React連接
鏈接地址:http://www.dlmjj.cn/article/copijod.html


咨詢
建站咨詢
