🔍 搜尋結果:導覽列

🔍 搜尋結果:導覽列

如何建構:人工智慧驅動的部落格平台(Next.js、Langchain 和 Supabase)

**長話短說** -------- 在本文中,您將學習如何建立一個人工智慧驅動的部落格平台,該平台可以搜尋網路並研究部落格文章的任何主題。 我們將涵蓋: - 用於應用程式框架的 Next.js 🖥️ - 法學碩士 OpenAI 🧠 - LangChain 和 Tavily 的網路搜尋人工智慧代理🤖 - 使用 CopilotKit 將 AI 整合到您的應用程式中 🪁 - Supabase 用於儲存和檢索部落格平台文章資料。 --- CopilotKit:開源 Copilot 框架 ======================== CopilotKit 是[開源 AI 副駕駛框架和平台。](https://github.com/CopilotKit/CopilotKit)我們可以輕鬆地將強大的人工智慧整合到您的 React 應用程式中。 建造: - ChatBots💬:上下文感知的應用內聊天機器人,可以在應用程式內執行操作 - CopilotTextArea📝:人工智慧驅動的文字字段,具有上下文感知自動完成和插入功能 - 聯合代理🤖:應用程式內人工智慧代理,可以與您的應用程式和使用者互動。由浪鏈提供技術支援。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i8gltoave8490fg234ro.gif) {% cta https://github.com/CopilotKit/CopilotKit %} Star CopilotKit ⭐️ {% endcta %} (原諒人工智慧的拼字錯誤並給一顆星:) 現在回到文章。 --- **先決條件** -------- 在開始建立應用程式之前,讓我們先查看建置應用程式所需的依賴項或套件 - `copilotkit/react-core` :CopilotKit 前端包,帶有 React hooks,用於向副駕駛提供應用程式狀態和操作(AI 功能) - `copilotkit/react-ui:`聊天機器人側邊欄 UI 的 CopilotKit 前端包 - `copilotkit/react-textarea:` CopilotKit 前端包,用於在演講者筆記中進行人工智慧輔助文字編輯。 - `LangChainJS:`用於開發由語言模型支援的應用程式的框架。 - `Tavily Search API:`幫助將法學碩士和人工智慧應用程式連接到可信賴的即時知識的 API。 安裝所有專案包和依賴項 ----------- 在安裝所有專案包和依賴項之前,我們首先在終端機上執行以下命令來建立 Nextjs 專案。 ``` npx create-next-app@latest ``` 然後系統會提示您選擇一些選項。請隨意標記它們,如下所示。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1j04grq2jykx6o606u1s.png) 之後,使用您選擇的文字編輯器開啟新建立的 Nextjs 專案。然後在命令列中執行以下命令來安裝所有專案包和依賴項。 ``` npm i @copilotkit/backend @copilotkit/shared @langchain/langgraph @copilotkit/react-core @copilotkit/react-ui @copilotkit/react-textarea @supabase/ssr @supabase/auth-helpers-nextjs ``` **建立部落格平台前端** ------------- 在本節中,我將引導您完成使用靜態內容建立部落格平台前端的過程,以定義平台的使用者介面。 首先,前往`/[root]/src/app`並建立一個名為`components`的資料夾。在 Components 資料夾中,建立一個名為`Article.tsx`的檔案。 之後,將以下程式碼新增至定義名為`Article`功能元件的檔案中,該元件將用於呈現文章建立表單。 ``` "use client"; import { useRef, useState } from "react"; export function Article() { // Define state variables for article outline, copilot text, and article title const [articleOutline, setArticleOutline] = useState(""); const [copilotText, setCopilotText] = useState(""); const [articleTitle, setArticleTitle] = useState(""); return ( // Form element for article input <form action={""} className="w-full h-full gap-10 flex flex-col items-center p-10"> {/* Input field for article title */} <div className="flex w-full items-start gap-3"> <textarea className="p-2 w-full h-12 rounded-lg flex-grow overflow-x-auto overflow-y-hidden whitespace-nowrap" id="title" name="title" value={articleTitle} placeholder="Article Title" onChange={(event) => setArticleTitle(event.target.value)} /> </div> {/* Textarea for article content */} <textarea className="p-4 w-full aspect-square font-bold text-xl bg-slate-800 text-white rounded-lg resize-none" id="content" name="content" value={copilotText} placeholder="Write your article content here" onChange={(event) => setCopilotText(event.target.value)} /> {/* Publish button */} <button type="submit" className="p-4 w-full !bg-slate-800 text-white rounded-lg">Publish</button> </form> ); } ``` 接下來,將另一個檔案新增到元件資料夾中,並將其命名為`Header.tsx` 。然後將以下程式碼新增至定義名為`Header`的功能元件的檔案中,該元件將呈現部落格平台的導覽列。 ``` import Link from "next/link"; export default function Header() { return ( <> <header className="flex flex-wrap sm:justify-start sm:flex-nowrap z-50 w-full bg-white border-b border-gray-200 text-sm py-3 sm:py-0 "> <nav className="relative max-w-7xl w-full mx-auto px-4 sm:flex sm:items-center sm:justify-between sm:px-6 lg:px-8" aria-label="Global"> <div className="flex items-center justify-between"> <Link className="flex-none text-xl font-semibold " href="/" aria-label="Brand"> AIBlogging </Link> </div> <div id="navbar-collapse-with-animation" className=""> <div className="flex flex-col gap-y-4 gap-x-0 mt-5 sm:flex-row sm:items-center sm:justify-end sm:gap-y-0 sm:gap-x-7 sm:mt-0 sm:ps-7"> <Link className="flex items-center font-medium text-gray-500 border-2 border-indigo-600 text-center p-2 rounded-md hover:text-blue-600 sm:border-s sm:my-6 " href="/writearticle"> Create Post </Link> </div> </div> </nav> </header> </> ); } ``` 之後,轉到`/[root]/src/app`並建立一個名為`writearticle`的資料夾。在`writearticle`資料夾中,建立一個名為`page.tsx`檔案。然後將以下程式碼加入匯入`Article`和`Header`元件的檔案中。然後,程式碼定義了一個名為`WriteArticle`的功能元件,它將呈現導覽列和文章建立表單。 ``` import { Article } from "../components/Article"; import Header from "../components/Header"; export default function WriteArticle() { return ( <> <Header /> <Article /> </> ); } ``` 接下來,前往`/[root]/src/page.tsx`文件,並新增以下程式碼,該程式碼定義一個名為`Home`功能元件,該元件呈現將顯示已發佈文章清單的部落格平台主頁。 ``` import Image from "next/image"; import Link from "next/link"; import Header from "./components/Header"; const Home = async () => { return ( <> <Header /> <div className="max-w-[85rem] h-full px-4 py-10 sm:px-6 lg:px-8 lg:py-14 mx-auto"> <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-6"> <Link key={""} className="group flex flex-col h-full bg-white border border-gray-200 hover:border-transparent hover:shadow-lg transition-all duration-300 rounded-xl p-5 " href={""}> <div className="aspect-w-16 aspect-h-11"> <Image className="object-cover h-48 w-96 rounded-xl" src={`https://source.unsplash.com/featured/?${encodeURIComponent( "hello world" )}`} width={500} height={500} alt="Image Description" /> </div> <div className="my-6"> <h3 className="text-xl font-semibold text-gray-800 "> Hello World </h3> </div> </Link> </div> </div> </> ); }; export default Home; ``` 之後,請轉到`next.config.js`檔案並加入以下程式碼,該程式碼允許您使用 Unsplash 中的圖像作為已發布文章的封面圖像。 ``` module.exports = { images: { remotePatterns: [ { protocol: "https", hostname: "source.unsplash.com", }, ], }, }; ``` 最後,在命令列上執行命令`npm run dev` ,然後導航到 http://localhost:3000/。現在您應該在瀏覽器上查看部落格平台前端,如下所示。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m319h0j3ta0xa1fhkezo.png) **將部落格平台與 CopilotKit 後端集成** --------------------------- 在本節中,我將引導您完成將部落格平台與 CopilotKit 後端整合的過程,CopilotKit 後端處理來自前端的請求,提供函數呼叫和各種 LLM 後端(例如 GPT)。此外,我們將整合一個名為 Tavily 的人工智慧代理,它可以研究網路上的任何主題。 首先,在根目錄中建立一個名為`.env.local`的檔案。然後在保存`ChatGPT`和`Tavily` Search API 金鑰的檔案中加入下面的環境變數。 ``` OPENAI_API_KEY="Your ChatGPT API key" TAVILY_API_KEY="Your Tavily Search API key" ``` 若要取得 ChatGPT API 金鑰,請導覽至 https://platform.openai.com/api-keys。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/co9getwdzh34u1k5cehf.png) 若要取得 Tavilly Search API 金鑰,請導覽至 https://app.tavily.com/home ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ju9syhy5w8oip67tyne0.png) 之後,轉到`/[root]/src/app`並建立一個名為`api`的資料夾。在`api`資料夾中,建立一個名為`copilotkit`的資料夾。在`copilotkit`資料夾中,建立一個名為`research.ts`的檔案。然後導航到[該 Research.ts gist 文件](https://gist.github.com/TheGreatBonnie/58dc21ebbeeb8cbb08df665db762738c),複製程式碼,並將其新增至**`research.ts`**檔案中 接下來,在`/[root]/src/app/api/copilotkit`資料夾中建立一個名為`route.ts`的檔案。該文件將包含設定後端功能來處理 POST 請求的程式碼。它有條件地包括對給定主題進行研究的“研究”操作。 現在在文件頂部導入以下模組。 ``` import { CopilotBackend, OpenAIAdapter } from "@copilotkit/backend"; // For backend functionality with CopilotKit. import { researchWithLangGraph } from "./research"; // Import a custom function for conducting research. import { AnnotatedFunction } from "@copilotkit/shared"; // For annotating functions with metadata. ``` 在上面的程式碼下面,定義一個執行時間環境變數和一個名為`researchAction`的函數,該函數使用下面的程式碼對某個主題進行研究。 ``` // Define a runtime environment variable, indicating the environment where the code is expected to run. export const runtime = "edge"; // Define an annotated function for research. This object includes metadata and an implementation for the function. const researchAction: AnnotatedFunction<any> = { name: "research", // Function name. description: "Call this function to conduct research on a certain topic. Respect other notes about when to call this function", // Function description. argumentAnnotations: [ // Annotations for arguments that the function accepts. { name: "topic", // Argument name. type: "string", // Argument type. description: "The topic to research. 5 characters or longer.", // Argument description. required: true, // Indicates that the argument is required. }, ], implementation: async (topic) => { // The actual function implementation. console.log("Researching topic: ", topic); // Log the research topic. return await researchWithLangGraph(topic); // Call the research function and return its result. }, }; ``` 然後在上面的程式碼下加入下面的程式碼來定義處理POST請求的非同步函數。 ``` // Define an asynchronous function that handles POST requests. export async function POST(req: Request): Promise<Response> { const actions: AnnotatedFunction<any>[] = []; // Initialize an array to hold actions. // Check if a specific environment variable is set, indicating access to certain functionality. if (process.env["TAVILY_API_KEY"]) { actions.push(researchAction); // Add the research action to the actions array if the condition is true. } // Instantiate CopilotBackend with the actions defined above. const copilotKit = new CopilotBackend({ actions: actions, }); // Use the CopilotBackend instance to generate a response for the incoming request using an OpenAIAdapter. return copilotKit.response(req, new OpenAIAdapter()); } ``` **將部落格平台與 CopilotKit 前端集成** --------------------------- 在本節中,我將引導您完成將部落格平台與 CopilotKit 前端整合的過程,以促進部落格文章研究和文章大綱生成。我們將使用聊天機器人側欄元件、copilot 文字區域元件、用於向 Copilot 提供應用程式狀態和其他資訊的 useMakeCopilotReadable 掛鉤,以及用於提供 Copilot 可以呼叫的操作的 useCopilotAction 掛鉤 首先,導入`/[root]/src/app/components/Article.tsx`檔案頂部的`useMakeCopilotReadable` 、 `useCopilotAction` 、 `CopilotTextarea`和`HTMLCopilotTextAreaElement`掛鉤。 ``` import { useMakeCopilotReadable, useCopilotAction, } from "@copilotkit/react-core"; import { CopilotTextarea, HTMLCopilotTextAreaElement, } from "@copilotkit/react-textarea"; ``` 在 Article 函數內的狀態變數下方,新增以下程式碼,該程式碼使用`useMakeCopilotReadable`掛鉤來新增將作為應用程式內聊天機器人的上下文產生的文章大綱。鉤子使副駕駛可以閱讀文章大綱。 ``` useMakeCopilotReadable("Blog article outline: " + JSON.stringify(articleOutline)); ``` 在`useMakeCopilotReadable`掛鉤下方,使用以下程式碼建立一個名為`copilotTextareaRef`的引用,該引用指向名為`HTMLCopilotTextAreaElement`的文字區域元素。 ``` const copilotTextareaRef = useRef<HTMLCopilotTextAreaElement>(null); ``` 在上面的程式碼下方,加入以下程式碼,該程式碼使用`useCopilotAction`掛鉤來設定名為`researchBlogArticleTopic`的操作,該操作將啟用對部落格文章的給定主題的研究。此操作採用兩個參數,稱為`articleTitle`和`articleOutline` ,這兩個參數可以產生文章標題和大綱。 該操作包含一個處理程序函數,該函數根據給定主題生成文章標題和大綱。在處理函數內部, `articleOutline`狀態會使用新產生的大綱進行更新,而`articleTitle`狀態會使用新產生的標題進行更新,如下所示。 ``` useCopilotAction( { name: "researchBlogArticleTopic", description: "Research a given topic for a blog article.", parameters: [ { name: "articleTitle", type: "string", description: "Title for a blog article.", required: true, }, { name: "articleOutline", type: "string", description:"Outline for a blog article that shows what the article covers.", required: true, }, ], handler: async ({ articleOutline, articleTitle }) => { setArticleOutline(articleOutline); setArticleTitle(articleTitle); }, }, [] ); ``` 在上面的程式碼下方,前往表單元件並新增以下`CopilotTextarea`元素,該元素將使您能夠為文章內容新增補全、插入和編輯。 ``` <CopilotTextarea value={copilotText} ref={copilotTextareaRef} placeholder="Write your article content here" onChange={(event) => setCopilotText(event.target.value)} className="p-4 w-full aspect-square font-bold text-xl bg-slate-800 text-white rounded-lg resize-none" placeholderStyle={{ color: "white", opacity: 0.5, }} autosuggestionsConfig={{ textareaPurpose: articleTitle, chatApiConfigs: { suggestionsApiConfig: { forwardedParams: { max_tokens: 5, stop: ["\n", ".", ","], }, }, insertionApiConfig: {}, }, debounceTime: 250, }} /> ``` 然後將Tailwindcss隱藏類別加入文章內容的Textarea中,如下所示。文字區域將保存文章的內容,並在文章發布後將其插入資料庫。 ``` {/* Textarea for article content */} <textarea className="p-4 w-full aspect-square font-bold text-xl bg-slate-800 text-white rounded-lg resize-none hidden" id="content" name="content" value={copilotText} placeholder="Write your article content here" onChange={(event) => setCopilotText(event.target.value)} /> ``` 之後,請前往`/[root]/src/app/writearticle/page.tsx`檔案並使用下面的程式碼匯入頂部的 CopilotKit 前端套件和樣式。 ``` import { CopilotKit } from "@copilotkit/react-core"; import { CopilotSidebar } from "@copilotkit/react-ui"; import "@copilotkit/react-ui/styles.css"; import "@copilotkit/react-textarea/styles.css"; ``` 然後使用`CopilotKit`和`CopilotSidebar`包裹Article元件,如下所示。 `CopilotKit`元件指定 CopilotKit 後端端點 ( `/api/copilotkit/openai/` ) 的 URL,而`CopilotSidebar`則呈現應用程式內聊天機器人,您可以提示您研究文章的任何主題。 ``` export default function WriteArticle() { return ( <> <Header /> <CopilotKit url="/api/copilotkit"> <CopilotSidebar instructions="Help the user research a blog article topic." defaultOpen={true} labels={{ title: "Blog Article Copilot", initial: "Hi you! 👋 I can help you research any topic for a blog article.", }} clickOutsideToClose={false}> <Article /> </CopilotSidebar> </CopilotKit> </> ); } ``` 之後,執行開發伺服器並導航到 http://localhost:3000/writearticle。您應該會看到應用程式內聊天機器人已整合到部落格平台中。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yx7m6fhxm9gdg942a0sq.png) 給右側的聊天機器人一個提示,例如“研究一篇關於生成人工智慧的部落格文章主題,然後給我文章大綱。”聊天機器人將開始研究該主題,然後產生部落格標題。 當您開始在編輯器上寫作時,您應該會看到內容自動建議,如下所示。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ocnhptqxnk5gopvlzfs8.png) **將部落格平台與 Supabase 資料庫集成** -------------------------- 在本節中,我將引導您完成將部落格平台與 Supabase 資料庫整合以插入和獲取部落格文章資料的過程。 首先,導覽至[supabase.com](http://supabase.com)並點擊主頁上的「啟動您的專案」按鈕。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/95n06a6aj55r5w959gz6.png) 然後新建一個專案,名為AiBloggingPlatform,如下圖所示。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lifhztowgy3g1v9wwnjk.png) 建立專案後,將 Supabase URL 和 API 金鑰新增至 env.local 檔案中的環境變數中,如下所示。 ``` NEXT_PUBLIC_SUPABASE_URL=”Your Supabase URL” NEXT_PUBLIC_SUPABASE_ANON_KEY=”Your Supabase API Key” ``` 之後,請前往 Supabase 上專案的儀表板並開啟 SQL 編輯器部分。然後將下列 SQL 程式碼新增至編輯器中,然後按一下 CTRL + Enter 鍵建立一個名為articles 的表。文章表包含 id、標題和內容行。 ``` create table if not exists articles ( id bigint primary key generated always as identity, title text, content text ); ``` 建立表格後,您應該會收到一條成功訊息,如下所示。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bjb84czwivk6ue7duj0b.png) 之後,轉到`/[root]/src/`資料夾並建立一個名為`utils`的資料夾。在`utils`資料夾內,建立一個名為`supabase.ts`文件,並新增以下用於建立並傳回 Supabase 用戶端的程式碼。 ``` // Importing necessary functions and types from the Supabase SSR package import { createServerClient, type CookieOptions } from '@supabase/ssr' // Define a function named 'supabase' that takes a 'CookieOptions' object as input export const supabase = (cookies: CookieOptions) => { // Retrieve cookies from the provided 'CookieOptions' object const cookieStore = cookies() // Create and return a Supabase client configured with environment variables and cookie handling return createServerClient( // Retrieve Supabase URL from environment variables process.env.NEXT_PUBLIC_SUPABASE_URL!, // Retrieve Supabase anonymous key from environment variables process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!, { cookies: { // Define a custom 'get' function to retrieve cookies by name from the cookie store get(name: string) { return cookieStore.get(name)?.value }, }, } ) } ``` 然後轉到`/[root]/src/app`資料夾並建立一個名為`serveractions`的資料夾。在`serveractions`資料夾中,建立一個名為`AddArticle.ts`的文件,並新增以下程式碼,將部落格文章資料插入到 Supabase 資料庫中。 ``` // Importing necessary functions and modules for server-side operations "use server"; import { createServerComponentClient } from "@supabase/auth-helpers-nextjs"; import { cookies } from "next/headers"; import { redirect } from "next/navigation"; // Define an asynchronous function named 'addArticle' that takes form data as input export async function addArticle(formData: any) { // Extract title and content from the provided form data const title = formData.get("title"); const content = formData.get("content"); // Retrieve cookies from the HTTP headers const cookieStore = cookies(); // Create a Supabase client configured with the provided cookies const supabase = createServerComponentClient({ cookies: () => cookieStore }); // Insert the article data into the 'articles' table on Supabase const { data, error } = await supabase.from("articles").insert([ { title, content, }, ]); // Check for errors during the insertion process if (error) { console.error("Error inserting data", error); return; } // Redirect the user to the home page after successfully adding the article redirect("/"); // Return a success message return { message: "Success" }; } ``` 之後,轉到`/[root]/src/app/components/Article.tsx`檔案並導入`addArticle`函數。 ``` import { addArticle } from "../serveractions/AddArticle"; ``` 然後加入`addArticle`函數作為表單動作參數,如下所示。 ``` // Form element for article input <form action={addArticle} className="w-full h-full gap-10 flex flex-col items-center p-10"> </form> ``` 之後,導覽至http://localhost:3000/writearticle,研究您選擇的主題,新增文章內容,然後點擊底部的發布按鈕來發布文章。 然後轉到 Supabase 上專案的儀表板並導航到表編輯器部分。您應該會看到您的文章資料已插入 Supabase 資料庫,如下所示。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fklcuyv5q5eq1ajmdjyv.png) 接下來,前往`/[root]/src/app/page.tsx`檔案並在頂部導入 cookie 和 supabase 套件。 ``` import { cookies } from "next/headers"; import { supabase } from "@/utils/supabase"; ``` 然後在 Home 函數中加入以下程式碼,從 Supabase 資料庫中取得文章資料。 ``` const { data: articles, error } = await supabase(cookies).from('articles').select('*') ``` 之後,更新如下所示的元素程式碼,以將已發佈的文章呈現在部落格平台主頁上。 ``` return ( <> <Header /> <div className="max-w-[85rem] h-full px-4 py-10 sm:px-6 lg:px-8 lg:py-14 mx-auto"> <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-6"> {articles?.map((post: any) => ( <Link key={post.id} className="group flex flex-col h-full bg-white border border-gray-200 hover:border-transparent hover:shadow-lg transition-all duration-300 rounded-xl p-5 " href={`/posts/${post.id}`}> <div className="aspect-w-16 aspect-h-11"> <Image className="object-cover h-48 w-96 rounded-xl" src={`https://source.unsplash.com/featured/?${encodeURIComponent( post.title )}`} width={500} height={500} alt="Image Description" /> </div> <div className="my-6"> <h3 className="text-xl font-semibold text-gray-800 "> {post.title} </h3> </div> </Link> ))} </div> </div> </> ); ``` 然後導航到[http://localhost:3000](http://localhost:3000/writearticle) ,您應該會看到您發布的文章,如下所示。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/429bilwyje2a4xh0il5n.png) 之後,轉到`/[root]/src/app`資料夾並建立一個名為`[id].`在`[id]`資料夾中,建立一個名為`page.tsx`的文件,並在頂部匯入以下套件和元件。 ``` import { supabase } from '@/utils/supabase'; import { cookies } from "next/headers"; import Header from '@/app/components/Header'; ``` 在導入下面,定義一個名為「getArticles」的非同步函數,該函數根據 id 參數從 supabase 資料庫檢索文章資料,如下所示。 ``` // Define an asynchronous function named 'getArticles' that retrieves article data based on the provided parameters async function getArticles(params: any) { // Extract the 'id' parameter from the provided 'params' object const { id } = params // Retrieve article data from Supabase database where the 'id' matches the provided value const { data, error } = await supabase(cookies) .from('articles') .select('*') .eq('id', id) .single(); // Return the retrieved data return data } ``` 在上面的程式碼下面,定義一個名為“Post”的函數,它將“params”作為 props,如下所示。 ``` // Define a default asynchronous function named 'Post' that takes 'params' as props export default async function Post({ params }: { params: any }) { // Retrieve the post data asynchronously based on the provided 'params' const post = await getArticles(params); // Return JSX to render the post details return ( <> {/* Render the header component */} <Header /> {/* Main content wrapper */} <div className="max-w-3xl px-4 pt-6 lg:pt-10 pb-12 sm:px-6 lg:px-8 mx-auto"> <div className="max-w-2xl"> <div className="space-y-5 md:space-y-8"> <div className="space-y-3"> {/* Render the post title */} <h2 className="text-2xl font-bold md:text-3xl dark:text-white"> {/* Render the post title only if 'post' is truthy */} {post && post.title} </h2> {/* Render the post content */} <p className="text-lg text-gray-800 dark:text-gray-200"> {/* Render the post content only if 'post' is truthy */} {post && post.content} </p> </div> </div> </div> </div> </> ); } ``` 之後,導覽至[http://localhost:3000](http://localhost:3000/writearticle)並點擊部落格平台主頁上顯示的文章。 然後您應該被重定向到文章的內容,如下所示。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ojie4iwb8qn56gd2a907.png) 結論 -- 總而言之,您可以使用 CopilotKit 建立應用內 AI 聊天機器人,該機器人可以查看當前應用程式狀態並在應用程式內執行操作。 AI 聊天機器人可以與您的應用程式前端、後端和第三方服務對話。 完整的原始碼:https://github.com/TheGreatBonnie/aipoweredblog --- 原文出處:https://dev.to/copilotkit/how-to-build-an-ai-powered-blogging-platform-nextjs-langchain-supabase-1hdp

在 React 中編寫乾淨、可重複使用的元件(最佳實踐)

🔑 關鍵概念 ------ 什麼是可重複使用的 React 元件?您可以將它們視為建置塊。 它們是獨立的程式碼片段,可以在整個網站中重複使用,以節省您的時間和精力。 它們可以是從簡單按鈕到複雜表單的任何內容。 **為什麼要使用可重複使用的元件?** 隨著您的網站的發展,您可以透過組合現有元件輕鬆加入新功能。這使您的程式碼更具可擴展性和適應性。 您可以**在未來的專案中使用可重複使用的程式碼,**而無需從頭開始重新編寫。 --- 🧩 如何寫出乾淨、可重複使用的 React 元件 ------------------------ 在編寫乾淨的可重複使用 React 元件時,需要記住以下*兩個最重要的*事情: ![React 可重複使用元件的圖像](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yuprsf67nntkgexmo92w.jpg) **1. 🩼避免副作用。**不要將與外部資料互動的邏輯(例如進行 API 呼叫)直接放入可重複使用元件中。相反,將此邏輯作為`props`傳遞給元件。 例如,如果一個按鈕不僅僅是看起來漂亮,例如從網路獲取資料,**那麼它可能無法重複使用。** 在您掌握透過最佳實踐傳遞 props 的概念之前,我不會向您展示這方面的範例。繼續閱讀。 這是一個可重複使用的按鈕元件。但它缺乏最佳實踐。我將在範例部分向您展示原因。 ``` // This is a reusable button component (bad practice!) const Button = () => { return ( <button> Click Me </button> ); } ``` ‍ **2. 🗃️使用 props。** Props 是傳遞給元件以自訂其行為和外觀的參數。這允許您將相同的元件用於不同的目的。 ``` // This is a button component that can change its color const Button = ({ color }) => { return ( <button style={{ backgroundColor: color }}> Click Here </button> ); } ``` 這仍然是一個不好的做法,因為您有一個名為「點擊這裡」的固定標籤。如果您想更改按鈕上的文本,例如“註冊”,那麼您必須返回按鈕元件並進行更改。 這意味著每次我們想要使用不同的文字時,我們都必須返回並編輯程式碼。換句話說,它不再可重複使用。 **💪 挑戰:**那麼解決方案是什麼? 你已經有了答案。但如果您不這樣做,我將在範例部分向您展示。 **🌴提示:**考慮一下您可能希望如何在不同情況下使用該元件,並將其設計得靈活且適應性強。 🍃可重複使用 React 元件的範例 ------------------ 以下是可重複使用 React 元件的一些常見範例,以及一些幫助您入門的程式碼範例: **1. 按鈕:**具有不同樣式和功能的基本按鈕。 ``` // Button component import React from "react"; const Button = ({ color, label, onClick }) => { return ( <button className={`padding-2 shadow-none hover:shadow background-light-${color} hover:background-dark-${color}`} onClick={onClick} > {label} </button> ); }; export default Button; // Using the Button component <Button color="blue" label="Click Here" onClick={() => console.log("Button clicked!")} /> ``` 正如你所看到的,我沒有在按鈕元件中寫“Click Here”。我想讓我的按鈕可重複使用,因此它不知道有關自訂樣式或文字的任何資訊。 因此,我將它們作為 props(例如,顏色、標籤、onClick)傳遞,以便將來更改它們,而無需觸摸原始按鈕元件。希望這能說清楚。 > **🪜解決方案:**您需要將每個功能作為可重複使用元件中的`props`傳遞 - 就是這樣。 **2. 導覽列:**在整個網站上提供一致導覽的導覽列。 ``` // Navbar component import React from "react"; const Navbar = ({ isLoggedIn }) => { return ( <div className="navbar"> <div className="navbar-container"> <div className="navbar-logo"> <img src={logo} alt="logo" /> </div> <div className="navbar-links"> <a href="/">Home</a> <a href="/about">About</a> <a href="/contact">Contact</a> {isLoggedIn ? ( <a href="/profile">Profile</a> ) : ( <a href="/login">Login</a> )} </div> </div> </div> ); }; export default Navbar; // Using the Navbar component <Navbar isLoggedIn={true} /> ``` 如您所見,我通過了`<Navbar isLoggedIn={true} />` 此行利用`Navbar`元件並傳遞值為 true 的`isLoggedIn`屬性,表示使用者已登入。這將顯示「個人資料」連結並隱藏「登入」連結。 與按鈕元件類似,導覽列元件是可重複使用的,並接受 props 來自訂其行為。完美的! **3. 為什麼在按鈕元件中呼叫 API 是不好的做法** 現在,您已經了解了 React 中可重複使用元件的所有內容。 讓我們透過解決一個複雜的問題來更深入地研究。 考慮這樣的場景,您有一個執行 API 呼叫的按鈕。按鈕元件的程式碼可以如下: ``` import React from "react"; import doAPICall from "../api" const SaveButton = () => { return ( <button onClick={() => { doAPICall(); }} > Save </button> ); } export default SaveButton ``` 很明顯,您不能在多個地方重複使用上述按鈕,因為該按鈕元件內部包含副作用( `doAPICall()` )。 為了使該元件可重複使用,首先,您必須提取副作用並將其作為 prop 傳遞給按鈕元件,如下所示: ``` const App = () => { function doAPICall() { // Does an API call to save the current state of the app. } return ( <div> <SaveButton onClick={doAPICall}/> </div> ) } ``` 按鈕元件將如下所示: ``` const SaveButton = ({ onClick }) => { return ( <button onClick={onClick} > Save </button> ); } ``` 正如您所看到的,現在可以在您想要透過點擊按鈕儲存資料的所有位置重複使用上面的按鈕。該按鈕現在可以在多個地方像這樣使用: ``` const App = () => { function saveUser() { // Does an API call to save the user. } function saveProject() { // Does an API call to save the project. } return ( <div> <SaveButton onClick={saveUser}/> <SaveButton onClick={saveProject}/> </div> ) } ``` 您也可以透過使用 prop 來控制標籤,使按鈕元件更具可重複使用性,如下所示: ``` const App = () => { function saveUser() { // Does an API call to save the user. } function saveProject() { // Does an API call to save the project. } return ( <div> <SaveButton onClick={saveUser} label="Save user" /> <SaveButton onClick={saveProject} label="Save project" /> </div> ) } ``` 按鈕元件將如下所示: ``` const SaveButton = ({ onClick, label }) => { return ( <button onClick={onClick} > {label} </button> ); } ``` **🫧 推薦:🤖🦾 [Figma AI:](https://psxid.figma.com/8g4g75niz3sg-7v0ro9)** 如果您需要快速設計簡報或網站,Figma AI 可以提供現成的範本。並且它可以與[Figma](https://psxid.figma.com/pq1612tcamkx)順利配合。只要告訴它你想要什麼,畫一點,然後繁榮——你的想法就變成現實了! ![Figma AI 影像](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7cj5cxhykwmfnmve77co.png) 您可以嘗試[Figma AI](https://psxid.figma.com/8g4g75niz3sg-7v0ro9) ,目前它對所有人免費。 --- 👏結論 --- 恭喜!您已經成功學習如何使用最佳實踐建立乾淨的可重複使用 React 元件。 請記住,**可重複使用元件是健壯的 React 開發的建置塊**。透過練習可重複使用元件,您可以建立更乾淨、更有效率、更易於維護的 React 應用程式。 您練習得越多,您就越能更好地辨識在專案中使用它們的機會! 如果您喜歡這篇文章,您可能也會喜歡我的[𝕏](https://twitter.com/shahancd)帳戶,以了解更多有關前端開發的課程。 **閱讀更多:**[前端開發的未來](https://dev.to/codewithshahan/the-future-of-frontend-development-1amd) --- 原文出處:https://dev.to/codewithshahan/writing-clean-reusable-components-in-react-best-practices-2gka

Github Desktop 新手入門教學:第1課 ── 學會專案初始化

## 課程目標 - 學會專案初始化 ## 課程內容 在開始之前,我先再次說明一下 Git 與 Github Desktop 的不同 Git 是軟體工程師每天都會用到的,強大的專案版本管理工具,本身是命令列工具,要一直在終端機打指令 Github Desktop 是 Github 公司,為了方便入門者,所開發的 GUI(圖形化介面)工具,用起來簡單很多 本課程會交替使用這兩個名詞,前者代表 Git 正在發揮作用,後者代表正在操作 Github Desktop 功能 有點分不清楚沒關係,反正就知道有這差別即可,日後經驗更多,會越來越清楚 --- 讓我們開始玩玩看 Github Desktop 吧! 請先前往官網下載並安裝 https://desktop.github.com/ 在登入 Github 帳號的步驟,先選 `Skip this step` 跳過就好,我們後面課程再登入就好 --- 進入到 Github Desktop 主畫面之後,首先我們要設定一下 git 基本資訊 也就是在用 git 管理專案紀錄時,每次提交變化時,當筆提交的「作者資訊」 請在 Github Desktop 上方的導覽列,選擇 `Preferences` 然後選擇 `Git` 把 `Name` 跟 `Email` 欄位填寫一下,然後點擊 `Save` 按鈕,就可以囉! --- 來建立第一個用 git 管理的專案吧! 在主畫面,點選 `Create a New Repository on your Hard Drive` `Name` 就輸入 `my-first-repo` `Description` 可以省略不填 `Local Path` 隨便選一個方便的路徑 其餘的選項都保持預設就好,不用勾選 `Create Repository` 點下去,就建立第一個專案資料夾囉! --- 請在電腦上,直接打開那個資料夾,然後在資料夾裡面新增一個檔案 `my-document-1.txt`,裡面放入以下內容 ``` 我的第一個筆記檔案 ``` 接著打開 Github Desktop 看看狀況 會看到 `Changes` 分頁下面,有出現 `my-document-1.txt` 這個檔案 然後右側的主視窗,有顯示出檔案內容 這代表 git 已經發現它的存在了 我們成功使用 git 開始追蹤專案的歷史變化了! 這是一個很好的開始,本課先做到這樣就好! ## 課後作業 假設你正在準備履歷表,整理一些自我介紹、經營個人品牌的檔案 請建立一個名為 `my-resume` 的資料夾,並使用 git 開始追蹤這個資料夾 請在其中建立一個 `me.txt` 的文字檔案,裡面放入以下內容 ``` # 我是誰 - 我是XXX,目前在自學程式設計 # 我的學歷 - 高中:積極高中 - 大學:品質大學 ``` 你應該會在 `Changes` 分頁看到檔案出現 然後在右側主視窗,看到文字檔案的內容 完成以上任務,你就完成這次的課程目標了! --- 交作業的方法: 請直接截圖 Github Desktop 視窗的內容,上傳到留言區

自學網頁の嬰兒教材:第3課 ── 網格系統:頁面分區塊排個版

# 第3課 課程目標 能夠用 Bootstrap 的網格系統做出多欄式排版、各種排版。 # 第3課 課程內容 業界工程師會去使用 Bootstrap,除了美感之外,通常還有一大理由就是想用它的網格系統。 以網頁設計常見的多欄式設計來說,手寫 html 跟 css 實在有點麻煩: [CSS DIV 兩欄式網頁排版](http://www.wibibi.com/info.php?tid=406) [CSS DIV 三欄式網頁排版設計](http://www.wibibi.com/info.php?tid=407) 所以來學習簡單好用的網格系統吧! 請閱讀以下教學的內容: https://www.w3schools.com/bootstrap5/bootstrap_grid_basic.php https://www.w3schools.com/bootstrap5/bootstrap_grid_system.php https://www.w3schools.com/bootstrap5/bootstrap_grid_examples.php https://getbootstrap.com/docs/5.3/layout/grid/ 內容不用全部讀完,也不用全部讀懂,把其中的程式碼貼一貼,把玩一下,能做出基本的多欄式網頁佈局即可。 # 第3課 作業 繼續承接之前的作業。我們在前幾課做出了 Yahoo 的新聞頁以及導覽列,這一課的作業有兩個。 ## 作業一 請繼續修改之前的作業,除了新聞內容與導覽列之外,請接著利用 Bootstrap 網格系統將整個頁面都做出來。 請至少將側邊推薦其他新聞的區塊做出來,其餘的可以省略。 ## 作業二 請再開一份 Glitch 專案,我們要做 Yahoo 新聞的首頁: https://tw.news.yahoo.com 我們要用 Yahoo 新聞首頁來練習多欄式排版。 請利用 Bootstrap 網格系統,將整個首頁的排版都切出來。 各個區塊的內容盡量省略、簡化,利用純文字或是 `<ul>、<li>` 清單元素,只放標題跟一些文字即可。 完成以上兩份作業,你就完成這次的課程目標了!

自學網頁の嬰兒教材:第1課 ── 安裝:網頁突然好美美

# 第1課 課程目標 學會安裝 Bootstrap。 # 第1課 課程內容 第一課只要學會如何安裝 Bootstrap 就可以了。 Bootstrap 安裝好之後,瀏覽器預設的 h1, h2, h3, p 等等基本元素的樣式就會被覆蓋。 會變成 Bootstrap 的預設樣式,會更漂亮。 在網頁中引入 Bootstrap 的 css 與 js 檔的方式有很多,其中最簡單的是直接引入 BootstrapCDN 的線上檔案,連下載檔案都不用。 請閱讀一些 Bootstrap 基本觀念: https://www.w3schools.com/bootstrap5/bootstrap_get_started.php https://www.w3schools.com/bootstrap5/bootstrap_typography.php 然後參考官網的 BootstrapCDN 段落: https://getbootstrap.com/docs/5.3/getting-started/download/ --- 對於引入外部檔案的觀念不熟悉的話,請參考這份的「External Style Sheet」段落: https://www.w3schools.com/css/css_howto.asp 以及這份的「JavaScript in External File」段落: https://www.tutorialspoint.com/javascript/javascript_placement.htm # 第1課 作業 請打開:[Yahoo奇摩新聞](https://tw.news.yahoo.com) 找一篇你喜歡的新聞,把新聞內容打出來。 接著打開 [Glitch](https://glitch.com/),用 Glitch 來寫這次的作業。 只要打出文章標題與內容就好,上方的導覽列、旁邊的新聞頭條那些區塊都不用。 做完之後,你會發現,雖然只用了 h1、p、br 等等基本元素,但是套用 Bootstrap 之後,整個畫面自動變漂亮了! 完成這些,你就完成這次的課程目標了!

自學網頁の嬰兒教材:第3課 ── 網頁排版

# 第3課 課程目標 學會使用div和span元素 能夠做出漂亮的排版 # 第3課 課程內容 用jsfiddle來練習: https://jsfiddle.net 這次要寫HTML跟CSS兩個區塊 請閱讀這份教材: [HTML Block and Inline Elements](http://www.w3schools.com/html/html_blocks.asp) 或是看中文版 [HTML 块](http://www.w3school.com.cn/html/html_blocks.asp) 接著開始學習版面配置: [學習 CSS 版面配置](http://zh-tw.learnlayout.com/) 把教學裡面的HTML、CSS程式碼,貼到 jsfiddle 裡面做練習,貼好之後按上面的 RUN 按鈕,就會在右下角的 Result 看到結果了。 讀完、練習完這份教學裡面的程式碼,就算是學會基本的網頁排版了。 # 第3課 作業 在第1、2課的作業,我們將風傳媒的文章內容做了出來,但是略過了上方的導覽列、旁邊的熱門文章等等區塊。 這次作業要延續那些作業,這次不只是文章內容,請將整個頁面都做出來。 注意:本週作業內容繁重許多,請至少將上方的導覽列、旁邊的熱門文章推薦區塊做出來,其餘的可以省略。 完成這些,你就完成這次的課程目標了! 注意: 有同學反應,jsfiddle的介面太窄,不方便排版 如果您也覺得jsfiddle不好用,可改用 [Glitch](https://glitch.com/) 來練習。 完成後請將您的 Glitch 專案發布,即可將網址分享出去。 小技巧: 您可以使用瀏覽器的開發者功能,觀察網站本身是怎麼寫的 例如:Google Chrome 請對著元素按右鍵 -> 檢查 多利用這個技巧觀察網站原始碼,對於學習本身很有幫助

自學網頁の嬰兒教材:第1課 ── HTML 輕入門

# 第1課 課程目標 學會 h1, h2. p, br 等等HTML元素的用法 學完之後,你將可以用HTML來替內容排版 # 第1課 課程內容 第一課只要學習最基本的HTML元素就可以了 請打開這個網站,用這個網站來開發你的網站: https://jsfiddle.net 共有HTML, CSS, JavaScript三塊可以寫,先只要寫HTML就好。 閱讀並且練習這五份教學的內容: [HTML Basic](http://www.w3schools.com/html/html_basic.asp) [HTML Elements](http://www.w3schools.com/html/html_elements.asp) [HTML Attributes](http://www.w3schools.com/html/html_attributes.asp) [HTML Headings](http://www.w3schools.com/html/html_headings.asp) [HTML Paragraphs](http://www.w3schools.com/html/html_paragraphs.asp) 不習慣看英文,可以改看這裡: [HTML 基础](http://www.w3school.com.cn/html/html_basic.asp) [HTML 元素](http://www.w3school.com.cn/html/html_elements.asp) [HTML 属性](http://www.w3school.com.cn/html/html_attributes.asp) [HTML 标题](http://www.w3school.com.cn/html/html_headings.asp) [HTML 段落](http://www.w3school.com.cn/html/html_paragraphs.asp) 把教學裡面的HTML程式碼,貼到 jsfiddle 裡面的 HTML 區域,貼好之後按上面的 RUN 按鈕,就會在右下角的 Result 看到結果。 讀完、練習完這五份教學裡面的程式碼,就算是學會HTML的基礎了 # 第1課 作業 前往這個網站:[風傳媒](https://www.storm.mg) 或者任何你覺得版面很漂亮的媒體網站 找一篇你喜歡的文章 接著打開jsfiddle,把jsfiddle當成 Microsoft Word文書編輯軟體來用,用HTML的段落、標題、換行等等元素,把文章排版打出來。 只要打出文章內容就好,上方的導覽列、旁邊的熱門文章那些區塊都不用。 完成這些,你就完成這次的課程目標了!

開發 React 時,推薦使用這些 Best Practices

在開發 React App 時,遵循一些 best practices 會使您的程式碼品質提高,這篇文章列出一些給您參考。 - 原文出處:https://dev.to/iambilalriaz/react-best-practices-ege # 強烈推薦 VS Code 作為 IDE Visual Studio Code 有幾個超好用的 React 功能。強大的外掛生態系,對開發者大有幫助: - Prettier - ES Lint - JavaScript (ES6) code snippets - Reactjs code snippets - Auto import # 使用 ES6 語法 程式碼越漂亮越好。在 JavaScript 中,採用 ES6 語法可以讓程式碼更簡潔。 ## Arrow Functions ``` // ES5 function getSum(a, b) { return a + b; } // ES6 const getSum = (a, b) => a + b; ``` ## Template Literal ``` // ES5 var name = "Bilal"; console.log("My name is " + name); // ES6 const name = "Bilal"; console.log(`My name is ${name}`); ``` ## const $ let const $ let 有各自的變數作用域。const 宣告的變數不能修改,let 宣告的變數可以修改。 ``` // ES5 var fruits = ["apple", "banana"]; // ES6 let fruits = ["apple", "banana"]; fruits.push("mango"); const workingHours = 8; ``` ## Object Destructuring ``` var person = { name: "John", age: 40, }; // ES5 var name = person.name; var age = person.age; // ES6 const { name, age } = person; ``` ## Defining Objects ``` var name = "John"; var age = 40; var designations = "Full Stack Developer"; var workingHours = 8; // ES5 var person = { name: name, age: age, designation: designation, workingHours: workingHours, }; // ES6 const person = { name, age, designation, workingHours }; ``` ES6 的語法特性、彈性,很多值得您一試。 # JSX 使用 map 時記得加上 key array map 時,永遠記得替每個元素加上獨立的 key 值。 ``` const students = [{id: 1, name: 'Bilal'}, {id: 2, name: 'Haris'}]; // in return function of component <ul> {students.map(({id, name}) => ( <li key={id}>{name}</li> ))} </ul>; ``` # 元件名稱使用 PascalCase ``` const helloText = () => <div>Hello</div>; // wrong const HelloText = () => <div>Hello</div>; // correct ``` # 變數和函數名稱使用 camelCase ``` const working_hours = 10; // bad approach const workingHours = 10; // good approach const get_sum = (a, b) => a + b; // bad approach const getSum = (a, b) => a + b; // good approach ``` # ID 和 css class 名稱使用 kebab-case ``` <!--bad approach--> <div className="hello_word" id="hello_world">Hello World</div> <!--good approach --> <div className="hello-word" id="hello-world">Hello World</div> ``` # 永遠要檢查物件&陣列的 null & undefined 忘記檢查的話,常常會導致一堆錯誤。 所以要保持檢查的習慣。 ``` const person = { name: "Haris", city: "Lahore", }; console.log("Age", person.age); // error console.log("Age", person.age ? person.age : 20); // correct console.log("Age", person.age ?? 20); //correct const oddNumbers = undefined; console.log(oddNumbers.length); // error console.log(oddNumbers.length ? oddNumbers.length : "Array is undefined"); // correct console.log(oddNumbers.length ?? "Array is undefined"); // correct ``` # 避免 Inline Styling Inline styling 會讓 jsx 程式碼變得很亂。用單獨的 css 文件拆分出來比較好。 ``` const text = <div style={{ fontWeight: "bold" }}>Happy Learing!</div>; // bad approach const text = <div className="learning-text">Happy Learing!</div>; // good approach ``` 在 .css 文件中: ``` .learning-text { font-weight: bold; } ``` # 避免 DOM 操作 用 React state 為主,別用 DOM 操作 糟糕做法: ``` <div id="error-msg">Please enter a valid value</div> ``` ``` document.getElementById("error-msg").visibility = visible; ``` 推薦做法: ``` const [isValid, setIsValid] = useState(false); <div hidden={isValid}>Please enter a valid value</div>; ``` 使用 isValid 來管理 UI 顯示邏輯。 # 在 useEffect 記得清乾淨每個事件監聽器 加過的事件監聽器,都要記得清乾淨: ``` const printHello = () => console.log("HELLO"); useEffect(() => { document.addEventListener("click", printHello); return () => document.removeEventListener("click", printHello); }); ``` # 避免重複開發,多寫通用元件 讓程式碼越乾淨越好。相似的東西可以寫通用元件。再根據 props 內容傳遞來處理相異處即可: ``` const Input=(props)=>{ const [inputValue, setInputValue]=useState(''); return( <label>{props.thing}</label> <input type='text' value={inputValue} onChange={(e)=>setInputValue(e.target.value)} /> ) } ``` 在其他元件中,就能這樣用: ``` <div> <Input thing="First Name" /> <Input thing="Second Name" /> </div> ``` # 檔案要分類一下 相關檔案可以分類成一個資料夾。 例如在 React 寫一個導覽列,那就可以開一個資料夾,相關的 .js 與 .css 檔案放裡面。 # 寫 functional components 為主 簡單顯示一些東西、沒用到 state 的話,那寫 functional components 比寫 class components 好。 如果你會寫 react hooks 的話,那就連 state 都完全不成問題。 # 養成編寫輔助函數的習慣 有時你在 React App 中會需要一些通用功能。 這種情況,可以開一個 `helper-functions.js` 檔案,在裡面寫輔助函數,就可以到處使用了。 ## 使用三元運算子代替 if/else if 使用 `if/else if` 語句會使程式碼變得龐大。使用三元運算子,就簡潔、清楚多了: ``` // Bad approach if (name === "Ali") { return 1; } else if (name === "Bilal") { return 2; } else { return 3; } // Good approach name === "Ali" ? 1 : name === "Bilal" ? 2 : 3; ``` # 新增 index.js 檔案,讓匯入元件更簡單 如果你在 actions 資料夾中有一個 index.js 檔案,當你想在元件中導入時,會像這樣: ``` import { actionName } from "src/redux/actions"; ``` actions 後面的 index.js 可以省略不寫,就不用這樣囉唆了: ``` import { actionName } from "src/redux/actions/index"; ``` # Destructuring of Props 物件屬性名稱可以拆出來,後面用起來比較方便。 假設你的元件有 `name`、`age` 和 `designation` 這些 props: ``` // Bad approach const Details = (props) => { return ( <div> <p>{props.name}</p> <p>{props.age}</p> <p>{props.designation}</p> </div> ); }; // Good approach const Details = ({ name, age, designation }) => { return ( <div> <p>{name}</p> <p>{age}</p> <p>{designation}</p> </div> ); }; ``` # 不要嘗試在同一函數中,去碰修改過的 state 變數 在一個函數中,如果你正在為一個狀態變數賦值,在同一個函數中,是拿不到新值的 ``` const Message = () => { const [message, setMessage] = useState("Hello World"); const changeMessage = (messageText) => { setMessage("Happy Learning"); console.log(message); // It will print Hello World on console }; return <div>{message}</div>; }; ``` # 使用 === 運算子代替 == 在比較兩個值時,嚴格檢查變數型別比較好: ``` "2" == 2 ? true : false; // true "2" === 2 ? true : false; // false ``` --- 以上 Best Practices 供您參考,祝福您不斷變強!