<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jamie Lo on Medium]]></title>
        <description><![CDATA[Stories by Jamie Lo on Medium]]></description>
        <link>https://medium.com/@jamielolo?source=rss-9dca7ca3c1ba------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gxsLLHbjO8wjjRwtSgH1LQ.png</url>
            <title>Stories by Jamie Lo on Medium</title>
            <link>https://medium.com/@jamielolo?source=rss-9dca7ca3c1ba------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 19:53:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jamielolo/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[【 PlantUML 】使用 PlantUML 生成 ERD]]></title>
            <link>https://medium.com/@jamielolo/plantuml-%E4%BD%BF%E7%94%A8-plantuml-%E7%94%9F%E6%88%90-erd-bbbd912b8bc2?source=rss-9dca7ca3c1ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbbd912b8bc2</guid>
            <category><![CDATA[plantuml]]></category>
            <dc:creator><![CDATA[Jamie Lo]]></dc:creator>
            <pubDate>Sat, 31 Aug 2024 09:31:59 GMT</pubDate>
            <atom:updated>2024-08-31T12:26:28.970Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FMEGn9IDalorTYLaowIHrg.jpeg" /><figcaption>Photo by Arnaud Rosques on <a href="https://zh.wikipedia.org/zh-tw/PlantUML">wikipedia</a></figcaption></figure><h4>前言</h4><p>曾使用線上畫圖工具畫序列圖與 ERD，um … 結果就是畫了很久，看起來好像有這麼一回事，又好像哪裡怪怪的，直到好友推薦了 PlantUML 這個好東西。</p><p>維基百科上面的介紹是：<br>PlantUML<strong> </strong>是可以用純文本語言繪製圖表的開源軟體。<br>PlantUML支援許多 <a href="https://zh.wikipedia.org/wiki/%E7%BB%9F%E4%B8%80%E5%BB%BA%E6%A8%A1%E8%AF%AD%E8%A8%80">統一建模語言</a>（UML）的圖，也支援其他軟體開發相關的格式。</p><p>個人認為對於工程師而言，與其自己用軟體拉拉畫畫，直接用寫的會直觀許多，除了能夠更好的釐清邏輯，也能更有效率地達成目標。</p><p>以下為使用 VS Code 的實作範例。</p><h4>前置作業</h4><ol><li>在 VS Code 安裝 <a href="https://marketplace.visualstudio.com/items?itemName=shd101wyy.markdown-preview-enhanced">Markdown Preview Enhanced</a> 與 <a href="https://marketplace.visualstudio.com/items?itemName=jebbs.plantuml">PlantUML</a> 這兩個擴充。</li><li>PlantUML 需要在 Java 環境下運行，以及安裝 Graphviz 來生成圖表，懶惰如我，選了另一個方案，也就是直接連上官方來渲染圖表。<br>在 VS Code 中開啟設置 ( 按 Cmd+, 或是 Ctrl+, )，搜尋 plantuml.server，將下面的網址貼在欄位上：<br>http://www.plantuml.com/plantuml</li><li>前往<a href="https://plantuml.com/zh/download#google_vignette">官網</a>下載 .jar 檔案，裡面有非常多種版本，筆者最後選擇的是限制較為寬鬆的 MIT 版本，下載後將檔案放在一個合理的位置。</li><li>開啟 VS Code 設置，搜尋 markdown-preview-enhanced.plantumlJarPath，並將你剛剛存放檔案的路徑寫上去，像筆者是使用 mac ，然後檔案放在文件資料夾裡，因此我要填上的是： /Users/jamie/Documents/plantuml-mit-1.2024.6.jar 。</li><li>在設置中搜尋 markdown-preview-enhanced.plantumlServer，填入 <a href="https://kroki.io/plantuml/svg/">https://kroki.io/plantuml/svg/</a> 。</li><li>在設置中搜尋 markdown-preview-enhanced.enableScriptExecution 並打勾選項。</li></ol><p>完成以上所有設置後，<strong>請重啟你的 VS Code</strong>，重啟後新增一個 ERD.md 檔案，在裡面放入以下內容後，點擊 VS Code 的預覽模式 ( 位於介面右上方，一個被切成兩等份的正方形，上面有放大鏡的 iocn。)。</p><pre>```plantuml<br>@startuml<br><br>entity &quot;Admins&quot; {<br>  *id : INTEGER [PK]<br>  --<br>  name : STRING<br>  account : STRING<br>  password : STRING<br>}<br><br>@enduml</pre><p>這時候會顯示出像下方這樣的頁面，這代表你成功完成了所有前置作業：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*srffCU3S0Z7b0TwZLZUWFg.png" /></figure><h4>創建實體</h4><p>首先，建立兩個簡單的實體，寫法如下：</p><pre>```plantuml<br>@startuml<br><br>entity &quot;Comments&quot; {<br>  *id : INTEGER [PK]<br>  --<br>  content : TEXT<br>  article_id : INTEGER [FK]<br>  user_id : INTEGER [FK]<br>}<br><br>entity &quot;Users&quot; {<br>  *id : INTEGER [PK]<br>  --<br>  name : STRING<br>  email : STRING<br>}<br><br>@enduml</pre><p>entity 指的是實體，{} 內則是用來定義你的資料欄位、型別、主鍵與外鍵 … 等，按照上面的文本內容，我們會獲得兩張圖表：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*jXNIXAveMeY3hPQC6fpD2Q.png" /></figure><h4>定義關聯</h4><p>在<a href="https://plantuml.com/zh/ie-diagram">官網</a>裡可以找到下面這張圖表，這是用來表達關聯的語法：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*9EVJVN-Bh4E39G-49zF_fQ.png" /></figure><p>以剛剛創建的兩個實體為例，它們之間的關聯定義如下：</p><ol><li>一位使用者可以留下多則評論，也可以不留下評論。</li><li>一則評論只會對應到一位使用者。</li></ol><p>對照上圖後，它們之間的關聯語法如下：</p><pre>Users ||--o{ Comments : &quot;has&quot;</pre><p>這邊的 has 只是一種敘述，代表一個使用者可以擁有多則評論，也可以改成你認為更合適的文字敘述。</p><p>把它加進我們剛剛的文件內，目前完整內容如下：</p><pre>```plantuml<br>@startuml<br><br>entity &quot;Comments&quot; {<br>  *id : INTEGER [PK]<br>  --<br>  content : TEXT<br>  article_id : INTEGER [FK]<br>  user_id : INTEGER [FK]<br>}<br><br><br>entity &quot;Users&quot; {<br>  *id : INTEGER [PK]<br>  --<br>  name : STRING<br>  email : STRING<br>}<br><br>Users ||--o{ Comments : &quot;has&quot;<br><br><br>@enduml</pre><p>生成的圖如下：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*FIOZbkYhNkKs4HF6GXLgEQ.png" /></figure><p>恭喜你，你已經成功學會如何使用 PlantUML 建立資料表間的關聯了！</p><h4>樣式設定</h4><p>PlantUML 可以客製化樣式。</p><ul><li><strong>改變全局樣式：</strong><br>在文件中加入 skinparam class ，現在所有的實體都會一起吃到這個樣式，變成我們所設定的背景顏色。</li></ul><pre>```plantuml<br>@startuml<br><br>skinparam class {<br>    BackgroundColor #FFD446<br>}<br><br>entity &quot;Comments&quot;  {<br>  *id : INTEGER [PK]<br>  --<br>  content : TEXT<br>  article_id : INTEGER [FK]<br>  user_id : INTEGER [FK]<br>}<br><br><br>entity &quot;Users&quot;  {<br>  *id : INTEGER [PK]<br>  --<br>  name : STRING<br>  email : STRING<br>}<br><br>Users ||--o{ Comments : &quot;has&quot;<br><br>@enduml</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*R4sTsFsC7l7GANQXpN6A0A.png" /></figure><ul><li><strong>改變局部樣式：<br></strong>可以透過 UML stereotype 來設置。<br>&lt;&lt;&gt;&gt; 表示 stereotype，這是 UML 中的一種機制，它可以為元素賦予特定的語意或標示。<br>以原先設計的例子來說，假設 Comments 並未實際在專案中創建，而是未來擴充的計畫之一，我們就可以用這樣的方式來表達。<br>請對照下方的文本與圖片，在 skinparam class 的樣式設定內加入 &lt;&lt;&gt;&gt;，裡面寫上對應的敘述，再把它加到我們的實體名稱後面，這樣樣式就會只套用到有指定該 stereotype 的實體上，並且在上面顯示你所輸入的敘述。</li></ul><pre>```plantuml<br>@startuml<br><br>skinparam class {<br>    BackgroundColor&lt;&lt;Future Enhancements&gt;&gt; #FFD446<br>}<br><br>entity &quot;Comments&quot; &lt;&lt;Future Enhancements&gt;&gt; {<br>  *id : INTEGER [PK]<br>  --<br>  content : TEXT<br>  article_id : INTEGER [FK]<br>  user_id : INTEGER [FK]<br>}<br><br><br>entity &quot;Users&quot; {<br>  *id : INTEGER [PK]<br>  --<br>  name : STRING<br>  email : STRING<br>}<br><br>Users ||--o{ Comments : &quot;has&quot;<br><br>@enduml</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*NIJaiBpD6efeF_W5WqkdFQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbbd912b8bc2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【 Google 】讓 Google Sheet 成為你的資料庫]]></title>
            <link>https://medium.com/@jamielolo/google-%E8%AE%93-google-sheet-%E6%88%90%E7%82%BA%E4%BD%A0%E7%9A%84%E8%B3%87%E6%96%99%E5%BA%AB-608073a472c2?source=rss-9dca7ca3c1ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/608073a472c2</guid>
            <category><![CDATA[google-sheets-api]]></category>
            <category><![CDATA[google-sheets]]></category>
            <category><![CDATA[google-apps-script]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Jamie Lo]]></dc:creator>
            <pubDate>Wed, 14 Jun 2023 03:55:37 GMT</pubDate>
            <atom:updated>2023-06-15T02:52:13.005Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8UvsAa8sSaxORXdQ" /><figcaption>Photo by <a href="https://unsplash.com/de/@prateekkatyal?utm_source=medium&amp;utm_medium=referral">Prateek Katyal</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>前言</h4><p>在工作上遇到了需要將前端收集到的資料整合給客戶的需求，最一開始是看了這篇 - <a href="https://ianccy.com/googleformapi/">Google sheet 試算表表單串接api</a>，但因為版本的更新，使用此篇做法會遇上 CORS 的問題，以下紀錄 2023 實測作法，大致操作與參考文章相同，主要的差別在於前端存取資料的部分。</p><p><a href="https://developers.google.com/apps-script/reference/spreadsheet/sheet?hl=zh-tw"><strong>官方文件在這裡</strong></a></p><h4>Google Apps Script</h4><p>1 . 建立一個新的 Google Sheet。<br>2 . 進入 Google 雲端硬碟頁面點選左上角的新增。<br>3 . 點選更多 ⇒ Google Apps Script</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*kg5XdnJZydVk0eZWEm4cIw.png" /></figure><p>4 . 以下為範例程式碼，請依實際需求修改資料格式：</p><pre>function doGet(e) {<br>  let name = e.parameters.name;<br>  let age = e.parameters.age;<br><br>  // 選擇 Google Sheet<br>  let spreadsheet = SpreadsheetApp.openById(&quot;填入Google Sheet ID&quot;);<br>  <br>  // 取得第一個表單<br>  let sheet = spreadsheet.getSheets()[0];<br>  // 目前的最後一行<br>  let lastRow = sheet.getLastRow();<br><br>  // 寫入資料，選擇 (行, 欄)。<br>  sheet.getRange(lastRow + 1, 1).setValue(name);<br>  sheet.getRange(lastRow + 1, 2).setValue(age);<br><br>  // result 裡面可以放入文字 debug，若成功送出請求，dev tools 將會打印出 result。<br>  let result = &quot;&quot;;<br>  let callback = e.parameters.callback;<br>  let response = callback + &quot;(&quot; + JSON.stringify(result) + &quot;)&quot;;<br>  return ContentService<br>    .createTextOutput(response)<br>    .setMimeType(ContentService.MimeType.JAVASCRIPT);<br>}</pre><p>Google Sheet 網址會有一段 ID，即下圖底線紅色的部分，請將上方程式碼中的 “填入Google Sheet ID” 改為你自己的 Google Sheet ID：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*NHacOGBp-kCSk3yxzRu_8g.png" /></figure><p>直接把程式碼寫在 gs 檔案裡：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*fR9K7C4iCFmnfFxF_BzBPA.png" /></figure><p>5 . 部署：點擊右上方的新增部署作業，<strong>每一次有更動都需要重新部署</strong>。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/196/1*7mWjeQ5VkMQlsPoBJzEQyg.png" /></figure><p>選取類型選擇網頁應用程式：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*em-Tmke5j3bpMH6HBWBTsA.png" /></figure><p>將存取權設為所有人：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*8v6WXtD-Xpt4_K_llLp6ug.png" /></figure><p>點擊部署之後會出現以下畫面，點擊授予存取權：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*qoT2Dvp-Ub4RS5t5TH3mYw.png" /></figure><p>接著會出現登入頁面，登入之後會看到下方畫面：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*W8rhKmM9yFiMFc3fyRAoCA.png" /></figure><p>請點擊左下角的 Advanced，然後前往專案，一路按允許確認：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*eXpFqwHALbtXPWAvOBgLzQ.png" /></figure><p>這時候會獲得一個網址，請將它複製起來，它就是前端要使用的網址：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*wbWT8ck2iW79yiWrhsz_Wg.png" /></figure><h4>前端部分</h4><p>使用 axios 會有 CORS 的問題，以下直接使用 js 連結遠端腳本，範例使用 React 寫法。</p><p>script.src 就是上一個步驟所複製的網址，請替換為你的網址並保留問號以後的程式碼：</p><p><strong>備註：每一次重新部署都會有新的網址。</strong></p><pre>function App() {<br>  window.handleResponse = (res) =&gt; {<br>    console.log(res)<br>  }<br>  const handleClick = () =&gt; {<br>    let data = { name: &#39;Jamie&#39;, age: 32 }<br>    let queryString = Object.keys(data)<br>      .map((key) =&gt; key + &#39;=&#39; + data[key])<br>      .join(&#39;&amp;&#39;)<br>    const script = document.createElement(&#39;script&#39;)<br>    script.src =<br>      &#39;https://script.google.com/macros/s/AKfycbzDuVg8vhVi88O6ErBIjTvljq_dBXtUqi-iKWl8aQyjYAOobsZcoiApYlBvQ61fbUoB/exec?&#39; +<br>      queryString +<br>      &#39;&amp;callback=handleResponse&#39;<br>    document.body.appendChild(script)<br>  }<br><br>  return (<br>    &lt;div className=&#39;App&#39;&gt;<br>      &lt;button onClick={handleClick}&gt;測試按鈕&lt;/button&gt;<br>    &lt;/div&gt;<br>  )<br>}<br><br>export default App</pre><p>若完全遵循上方操作，並替換為自己的 Google Sheet ID 以及部署網址，點擊畫面中的測試按鈕後，即可將資料送入 Google Sheet：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/1*wo7sxPvMu2qL0lPczovStw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=608073a472c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【 React 】Reducer 與 Context 的搭配使用]]></title>
            <link>https://medium.com/@jamielolo/react-reducer-%E8%88%87-context-%E7%9A%84%E6%90%AD%E9%85%8D%E4%BD%BF%E7%94%A8-5f58b24cd713?source=rss-9dca7ca3c1ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f58b24cd713</guid>
            <category><![CDATA[context]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reducer]]></category>
            <dc:creator><![CDATA[Jamie Lo]]></dc:creator>
            <pubDate>Thu, 16 Mar 2023 15:27:38 GMT</pubDate>
            <atom:updated>2023-03-16T15:27:38.477Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BYIwxX7PVYSl6Zk4" /><figcaption>Photo by <a href="https://unsplash.com/@miracleday?utm_source=medium&amp;utm_medium=referral">Elena Mozhvilo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>本篇筆記摘錄自官方文件 <a href="https://beta.reactjs.org/learn/scaling-up-with-reducer-and-context">Scaling Up with Reducer and Context</a></blockquote><p><a href="https://medium.com/@jamielolo/react-reducer-%E5%85%A5%E9%96%80-68dec141a6c0">Reducer</a> 讓你可以統一控管<a href="https://medium.com/@jamielolo/react-component-%E5%85%83%E4%BB%B6-4c572fcd4979">元件</a>的<a href="https://medium.com/@jamielolo/react-%E7%8B%80%E6%85%8B-state-30a8b791e4bc">狀態</a>更新，<a href="https://medium.com/@jamielolo/react-context-%E5%85%A5%E9%96%80-10cace64a054">Context</a> 讓你可以將資訊傳到位於結構較深處的元件，而你可以透過結合 reducer 與 context 來管理較複雜的狀態。</p><h4>Combining a reducer with context</h4><p>先前在 <a href="https://medium.com/@jamielolo/react-reducer-%E5%85%A5%E9%96%80-68dec141a6c0">Reducer 入門</a>篇時，我們有用過 reducer 來管理狀態，reducer 函式包含了所有的狀態更新邏輯：</p><p>( 將左側拉桿向右移動，可以看見程式碼的部分，拉開後點擊左上角三條線漢堡圖示可以看見完整檔案，右邊則為輸出結果。 )</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fnaughty-keldysh-u5b2fk%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fnaughty-keldysh-u5b2fk%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fu5b2fk%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/4013cf4d7d5f84394224154599ba8453/href">https://medium.com/media/4013cf4d7d5f84394224154599ba8453/href</a></iframe><p>reducer 可以讓<a href="https://medium.com/@jamielolo/react-%E4%BA%8B%E4%BB%B6%E7%9B%A3%E8%81%BD%E5%99%A8-responding-to-events-fa661a652f8">事件處理器</a>更加簡潔，然而，隨著專案的成長，你可能會遇到其他的困難，目前tasks狀態以及dispatch函式只能在TaskApp元件的最頂層取得，如果想讓其他元件也能閱讀或是改變，我們必須明確地將當前狀態以及事件處理器以 props 的方式傳遞下去。</p><p>舉例來說，TaskApp傳遞任務清單與事件處理器到TaskList：</p><pre>&lt;TaskList<br>  tasks={tasks}<br>  onChangeTask={handleChangeTask}<br>  onDeleteTask={handleDeleteTask}<br>/&gt;</pre><p>接著，TaskList再將事件處理器傳遞給Task：</p><pre>&lt;Task<br>  task={task}<br>  onChange={onChangeTask}<br>  onDelete={onDeleteTask}<br>/&gt;</pre><p>在這種小型的範例裡，這樣的做法是可以的，但如果中間必須穿越數十或數百個元件，這個方法將會非常的可怕。</p><p>這就是為什麼我們要將tasks狀態以及dispatch函式放進 context，使用這個方法，在TaskApp樹狀結構以下的所有元件都將能讀取tasks，以及進行dispatch actions，且不會產生 “prop drilling” 的情形。</p><p>我們可以透過以下幾個步驟來結合 reducer 與 context：</p><ol><li>建立 context</li><li>將狀態與 dispatch 放入 context</li><li>在該樹狀結構以下的任意地方使用 context</li></ol><h4>步驟一：建立 context</h4><p>useReducer會回傳當前的tasks與dispatch函式讓我們可以進行更新：</p><pre>const [tasks, dispatch] = useReducer(tasksReducer, initialTasks);</pre><p>為了傳遞它們，你需要創建兩個分開的 context：</p><ul><li>TasksContext提供目前的任務清單</li><li>TasksDispatchContext提供讓元件可以執行 dispatch actions 的函式</li></ul><p>分別匯出它們，之後就可以在其他的檔案匯入它們：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fgreen-firefly-1n71cs%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fgreen-firefly-1n71cs%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F1n71cs%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a498d8f82b97edb4870cf16b3910d3f/href">https://medium.com/media/7a498d8f82b97edb4870cf16b3910d3f/href</a></iframe><p>在這邊我們使用了null當作預設值，實際的值將會由TaskApp元件提供。</p><h4>步驟二：將狀態與 dispatch 放入 context</h4><p>把兩個 context 匯入TaskApp元件，並使用useReducer來 returntasks與dispatch，再將它們提供 ( provide ) 給該樹狀結構以下的所有元件：</p><pre>import { TasksContext, TasksDispatchContext } from &#39;./TasksContext.js&#39;;<br><br>export default function TaskApp() {<br>  const [tasks, dispatch] = useReducer(tasksReducer, initialTasks);<br>  // ...<br>  return (<br>    &lt;TasksContext.Provider value={tasks}&gt;<br>      &lt;TasksDispatchContext.Provider value={dispatch}&gt;<br>        ...<br>      &lt;/TasksDispatchContext.Provider&gt;<br>    &lt;/TasksContext.Provider&gt;<br>  );<br>}</pre><p>目前我們同時透過 props 與 context 來傳遞資訊，下個步驟我們將會把 props 傳遞的部分移除：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fkeen-antonelli-kfvrn7%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fkeen-antonelli-kfvrn7%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fkfvrn7%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/156f27dedc1a5e56570b065c06a73eb0/href">https://medium.com/media/156f27dedc1a5e56570b065c06a73eb0/href</a></iframe><h4>步驟三：在該樹狀結構以下的任意地方使用 context</h4><p>現在我們不再需要往下傳送任務清單或事件處理器：<br>( 這邊指的是傳到AddTask與TaskList)</p><pre>&lt;TasksContext.Provider value={tasks}&gt;<br>  &lt;TasksDispatchContext.Provider value={dispatch}&gt;<br>    &lt;h1&gt;Day off in Kyoto&lt;/h1&gt;<br>    &lt;AddTask /&gt;<br>    &lt;TaskList /&gt;<br>  &lt;/TasksDispatchContext.Provider&gt;<br>&lt;/TasksContext.Provider&gt;</pre><p>直接在需要任務清單的元件內讀取TaskContext：</p><pre>export default function TaskList() {<br>  const tasks = useContext(TasksContext);<br>  // ...</pre><p>元件可以讀取dispatch函式，並且透過呼叫它們來更新任務清單：</p><pre>export default function AddTask() {<br>  const [text, setText] = useState(&#39;&#39;);<br>  const dispatch = useContext(TasksDispatchContext);<br>  // ...<br>  return (<br>    // ...<br>    &lt;button onClick={() =&gt; {<br>      setText(&#39;&#39;);<br>      dispatch({<br>        type: &#39;added&#39;,<br>        id: nextId++,<br>        text: text,<br>      });<br>    }}&gt;Add&lt;/button&gt;<br>    // ...</pre><p>TaskApp 元件沒有向下傳遞任何事件處理器，而TaskList也沒有向Task傳遞任何事件處理器，它們各自透過 context 取得所需：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fobjective-tristan-8179bl%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fobjective-tristan-8179bl%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F8179bl%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/36f6666f6be91420899b93e2299c75ce/href">https://medium.com/media/36f6666f6be91420899b93e2299c75ce/href</a></iframe><p>狀態依舊會 “存活” 在TaskApp元件的頂層，並且使用useReducer來管理。<br>但是該樹狀結構以下的所有元件可以透過匯入以及使用 context，取得tasks與dispatch。</p><h4>Moving all wiring into a single file</h4><p>你不一定要這麼做，但你可以透過將 reducer 以及 context 移至單一檔案來進一步整理元件。</p><p>目前TaskContext.js檔案只包含了兩個 context 的宣告：</p><pre>import { createContext } from &#39;react&#39;;<br><br>export const TasksContext = createContext(null);<br>export const TasksDispatchContext = createContext(null);</pre><p>我們要將 reducer 一起移來這個檔案，接著在這個檔案宣告一個TasksProvider元件，這個元件將會連接起以下這些部分：</p><ol><li>它將會使用 reducer 來管理狀態。</li><li>它將會提供 context 給其他元件。</li><li>它會接收childrenprop，讓 JSX 可以傳遞進元件。</li></ol><pre>export function TasksProvider({ children }) {<br>  const [tasks, dispatch] = useReducer(tasksReducer, initialTasks);<br><br>  return (<br>    &lt;TasksContext.Provider value={tasks}&gt;<br>      &lt;TasksDispatchContext.Provider value={dispatch}&gt;<br>        {children}<br>      &lt;/TasksDispatchContext.Provider&gt;<br>    &lt;/TasksContext.Provider&gt;<br>  );<br>}</pre><p>以下為整理過後的程式碼：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Flingering-architecture-7pfy1j%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Flingering-architecture-7pfy1j%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F7pfy1j%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ff68e93081f355b37a40ebcad24e26e/href">https://medium.com/media/0ff68e93081f355b37a40ebcad24e26e/href</a></iframe><p>你也可以匯出函式，讓其他元件使用TaskContext.js裡的 context：</p><pre>export function useTasks() {<br>  return useContext(TasksContext);<br>}<br><br>export function useTasksDispatch() {<br>  return useContext(TasksDispatchContext);<br>}</pre><p>如果其他的元件需要讀取 context 就可以透過函式取得：</p><pre>const tasks = useTasks();<br>const dispatch = useTasksDispatch();</pre><p>現在所有的 context 與reducer 都已經在TaskContext.js整理好，這樣可以讓元件的內容更加乾淨、簡潔，更加專注於它們所要展示的，而不是資料的來源：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fhopeful-panna-nc64qd%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fhopeful-panna-nc64qd%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fnc64qd%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/1100eb7aa3e6b703d6d3ddf5cc81c9ca/href">https://medium.com/media/1100eb7aa3e6b703d6d3ddf5cc81c9ca/href</a></iframe><p>TasksProvider知道該如何處理這些任務們，useTasks用來讀取資訊，而useTasksDispatch用來更新該樹狀結構以下的任何元件。</p><p>像是useTasks以及useTasksDispatch這樣的函式被稱為 <a href="https://beta.reactjs.org/learn/reusing-logic-with-custom-hooks"><strong>Custom Hooks</strong></a>，沒錯，就是字面上的那個意思 - 自定義的 Hook。</p><blockquote>如果你的函式使用use為命名開頭，將會被視為一個自定義 Hook，這讓你可以在內部使用其他的 Hooks，像是useContext。</blockquote><p>隨著專案的成長，會有越來越多像這樣的 reducer 與 context 的搭配組合，不論想要取得資料的元件本身處於多深處的結構，這個方法讓我們可以不用透過過多的流程，就能達到 <a href="https://medium.com/@jamielolo/react-%E5%85%83%E4%BB%B6%E9%96%93%E7%9A%84%E7%8B%80%E6%85%8B%E5%88%86%E4%BA%AB-7f94b9b02139">lift state up</a> 的效果。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f58b24cd713" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【 React 】Context 入門]]></title>
            <link>https://medium.com/@jamielolo/react-context-%E5%85%A5%E9%96%80-10cace64a054?source=rss-9dca7ca3c1ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/10cace64a054</guid>
            <category><![CDATA[react-context]]></category>
            <category><![CDATA[usecontext]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Jamie Lo]]></dc:creator>
            <pubDate>Fri, 10 Mar 2023 17:24:02 GMT</pubDate>
            <atom:updated>2023-03-10T17:24:02.336Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pGDzZCEm2uHRslQz" /><figcaption>Photo by <a href="https://unsplash.com/@jplenio?utm_source=medium&amp;utm_medium=referral">Johannes Plenio</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>本篇筆記摘錄自官方文件 <a href="https://beta.reactjs.org/learn/passing-data-deeply-with-context">Passing Data Deeply with Context</a></blockquote><p>在先前的文章內，我們有提到如何使用 <a href="https://medium.com/@jamielolo/react-%E5%85%83%E4%BB%B6%E8%88%87-props-3b1200cec14d">props</a> 的方式，將資訊由父<a href="https://medium.com/@jamielolo/react-component-%E5%85%83%E4%BB%B6-4c572fcd4979">元件</a>傳送至子元件，如果需要接收資訊的子元件與父元件之間相隔多個元件，又或者是有多個子元件需要接收同一個資訊，原本的方式將會讓程式碼變得冗長且難以管理。</p><p>透過使用 Context，我們可以將資訊傳至任何子元件。</p><h4>The problem with passing prop</h4><p>傳遞 props 是一個透過 UI tree 傳遞資訊到其他子元件的好方法。</p><p>但當 props 傳遞的目標地點為樹狀結構深處，或是多個元件需要同一個 prop，就會使程式碼變得冗長，最近距離的共同父元件可能離需要資訊的子元件非常遠，從高處 <a href="https://medium.com/@jamielolo/react-%E5%85%83%E4%BB%B6%E9%96%93%E7%9A%84%E7%8B%80%E6%85%8B%E5%88%86%E4%BA%AB-7f94b9b02139">lifting state up</a> 的情形被稱為 “prop drilling”。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*6FWJ9EOqthyUfVFAUmhJXA.png" /></figure><p>有沒有辦法可以不透過這樣的方式來傳遞資料呢？<br>有的！context 就是為了解決這個問題而誕生的。</p><h4>Context: an alternative to passing props</h4><p>Context 讓父元件可以提供資料給該樹狀結構層底下的所有子元件。</p><p>下方的這個範例裡，Heading元件透過接收level來決定字體大小：</p><p>( 將左側拉桿向右移動，可以看見程式碼的部分，拉開後點擊左上角三條線漢堡圖示可以看見完整檔案，右邊則為輸出結果。 )</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fpolished-currying-l5glye%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fpolished-currying-l5glye%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fl5glye%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/7509992090de7be8c54244b68881f0cf/href">https://medium.com/media/7509992090de7be8c54244b68881f0cf/href</a></iframe><p>假設你希望同一個section裡的 headings 大小一致：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fcocky-roentgen-36blul%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fcocky-roentgen-36blul%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F36blul%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/55b5371eebd77af36bb9633e95b7f6df/href">https://medium.com/media/55b5371eebd77af36bb9633e95b7f6df/href</a></iframe><p>目前我們是將levelprop 分別傳入&lt;Heading&gt;：</p><pre>&lt;Section&gt;<br>  &lt;Heading level={3}&gt;About&lt;/Heading&gt;<br>  &lt;Heading level={3}&gt;Photos&lt;/Heading&gt;<br>  &lt;Heading level={3}&gt;Videos&lt;/Heading&gt;<br>&lt;/Section&gt;</pre><p>將levelprop移至&lt;Section&gt;元件會是一個比較好的做法，此方法可以確保相同的 section 裡，headings 擁有相同的大小：</p><pre>&lt;Section level={3}&gt;<br>  &lt;Heading&gt;About&lt;/Heading&gt;<br>  &lt;Heading&gt;Photos&lt;/Heading&gt;<br>  &lt;Heading&gt;Videos&lt;/Heading&gt;<br>&lt;/Section&gt;</pre><p>但是&lt;Heading&gt;要如何取得最接近&lt;Section&gt;裡的level呢？我們必須要有一些方法，讓子元件可以向該樹狀結構以上的某個地方 “請求” 資料。</p><p>單靠 props 是沒有辦法完成的，我們可以透過下面三個步驟來使用 context：</p><ol><li>創建 context<br>( 由於是用來存放 heading level，我們可以命名為LevelContext)</li><li>在需要資料的元件使用 context <br>(Heading將會使用LevelContext)</li><li>擁有指定資料的元件提供 ( provide ) context<br>(由Section提供LevelContext)</li></ol><p>Context 讓父元件可以提供資料給該樹狀結構以下的所有子元件。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*g-P6xV_1qWxGRnTc9HLZnA.png" /></figure><h4>步驟一：創建 context</h4><p>首先，創建 context，你需要將它從檔案匯出，這樣其他元件才能夠使用：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fadoring-wing-0ewru9%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fadoring-wing-0ewru9%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F0ewru9%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/5de809f472358651f3cdf2204d239c45/href">https://medium.com/media/5de809f472358651f3cdf2204d239c45/href</a></iframe><p>createContext的唯一引數為預設值，這邊的1指的是最大的 heading level，你可以傳入任何類型的值 ( 物件也可以 )。</p><h4>步驟二：使用 context</h4><p>匯入useContext 以及你的 context：</p><pre>import { useContext } from &#39;react&#39;;<br>import { LevelContext } from &#39;./LevelContext.js&#39;;</pre><p>目前Heading元件是從 props 取得 level：</p><pre>export default function Heading({ level, children }) {<br>  // ...<br>}</pre><p>請移除levelprop，改為使用剛剛匯入的LevelContext：</p><pre>export default function Heading({ children }) {<br>  const level = useContext(LevelContext);<br>  // ...<br>}</pre><p>useContext是一個 Hook，就跟useState與useReducer一樣，你只能在元件的最頂層呼叫它們，useContext 將會告訴 React，Heading元件想要讀取LevelContext。</p><p>現在Heading元件不再使用levelprop，我們不再需要像下方這樣在 JSX 中傳遞 level prop 給Heading：</p><pre>&lt;Section&gt;<br>  &lt;Heading level={4}&gt;Sub-sub-heading&lt;/Heading&gt;<br>  &lt;Heading level={4}&gt;Sub-sub-heading&lt;/Heading&gt;<br>  &lt;Heading level={4}&gt;Sub-sub-heading&lt;/Heading&gt;<br>&lt;/Section&gt;</pre><p>改由Section來接收 level：</p><pre>&lt;Section level={4}&gt;<br>  &lt;Heading&gt;Sub-sub-heading&lt;/Heading&gt;<br>  &lt;Heading&gt;Sub-sub-heading&lt;/Heading&gt;<br>  &lt;Heading&gt;Sub-sub-heading&lt;/Heading&gt;<br>&lt;/Section&gt;</pre><p>提醒，目前我們嘗試運作的標記式語言長這樣：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fclever-wright-jydicj%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fclever-wright-jydicj%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fjydicj%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/b386c92c6634609848800fd021512462/href">https://medium.com/media/b386c92c6634609848800fd021512462/href</a></iframe><p>透過結果可以發現，目前尚未達成我們想要的樣貌，目前所有 heading 的大小都是一樣的，這是因為雖然我們已經使用了 context，但我們尚未提供 ( provide ) context，React 並不知道要從哪裡取得資訊。</p><p>如果沒有提供 context，React 將會使用我們在步驟一所設置的預設值，在這個範例裡，我們將createContext的引數設置為1，所以useContext(LevelContext)會回傳1，這會使得所有的 heading 都被設為&lt;h1&gt; ，我們可以透過提供 context 給Section來解決這個問題。</p><h4>步驟三：Provide the context</h4><p>目前Section元件渲染著它的 children：</p><pre>export default function Section({ children }) {<br>  return (<br>    &lt;section className=&quot;section&quot;&gt;<br>      {children}<br>    &lt;/section&gt;<br>  );<br>}</pre><p>請使用 context provider 將它們包覆起來，將LevelContext提供給它們：</p><pre>import { LevelContext } from &#39;./LevelContext.js&#39;;<br><br>export default function Section({ level, children }) {<br>  return (<br>    &lt;section className=&quot;section&quot;&gt;<br>      &lt;LevelContext.Provider value={level}&gt;<br>        {children}<br>      &lt;/LevelContext.Provider&gt;<br>    &lt;/section&gt;<br>  );<br>}</pre><p>這將會告訴 React：如果&lt;Section&gt;內的任何元件對LevelContext提出請求，請給它們這個level。</p><p>元件將會使用該 UI tree 結構以上最接近的&lt;LevelContext.Provider&gt;所提供的值。<br>( 如果到這邊覺得不是很好理解，可以繼續往下看範例，透過實際範例將會好理解許多。)</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fdark-microservice-ehit2d%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fdark-microservice-ehit2d%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fehit2d%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d9d04c1b31c66226a4b0ba353d2e17f/href">https://medium.com/media/9d9d04c1b31c66226a4b0ba353d2e17f/href</a></iframe><p>輸出結果與一開始的範例是相同的，但我們不再需要向每個Heading傳遞levelprop，它會透過請求父層中最接近的Section來 “計算” 出 heading 大小：</p><ol><li>傳遞levelprop 到 &lt;Section&gt;</li><li>Section將它的 children 包進&lt;LevelContext.Provider value={level}&gt;</li><li>Heading透過useContext(LevelContext)請求最靠近的LevelContext值</li></ol><h4>Using and providing context from the same component</h4><p>目前我們是透過手動指定 section 的level：</p><pre>export default function Page() {<br>  return (<br>    &lt;Section level={1}&gt;<br>      ...<br>      &lt;Section level={2}&gt;<br>        ...<br>        &lt;Section level={3}&gt;<br>          ...</pre><p>由於 context 讓我們可以從父層取得資料，且每一個Section都能從父層Section取得level，因此我們可以改為傳遞level + 1，讓它自動的傳遞下去：</p><p>( 預設值改為 0，這樣一層一層包下去就會變成 h1 ~ h6，因為 context 會找最接近的父層。 )</p><pre>import { useContext } from &#39;react&#39;;<br>import { LevelContext } from &#39;./LevelContext.js&#39;;<br><br>export default function Section({ children }) {<br>  const level = useContext(LevelContext);<br>  return (<br>    &lt;section className=&quot;section&quot;&gt;<br>      &lt;LevelContext.Provider value={level + 1}&gt;<br>        {children}<br>      &lt;/LevelContext.Provider&gt;<br>    &lt;/section&gt;<br>  );<br>}</pre><p>使用這樣的方法，我們將不必再傳遞level至&lt;Section&gt;與&lt;Heading&gt;：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fserene-albattani-sbhymf%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fserene-albattani-sbhymf%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fsbhymf%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1bded6f2c4de910738a601cc217662c/href">https://medium.com/media/d1bded6f2c4de910738a601cc217662c/href</a></iframe><p>範例選用 heading level 是因為在視覺上能夠看出明顯的差異，context 可以用在許多地方，你可以使用它來傳遞資訊到所有 subtree，像是主題顏色，或是目前登入的使用者是誰 … 等。</p><p>( subtree 指的是該樹狀結構以下的內容，以 root 來說，所有的內容都是它的 subtree。)</p><h4>Context passes through intermediate components</h4><p>你可以在 provide context 的元件間放入任何需要的元件，包含像是&lt;div&gt;這樣的內建元件，以及你自己所建立的元件。</p><p>以下方的範例來說，同樣的Post( 虛線外框 ) 渲染在兩個不同的巢狀 level，請注意裡面的&lt;Heading&gt;，它的level是自動透過最接近的&lt;Section&gt;獲得：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fthrobbing-violet-8t0nb9%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fthrobbing-violet-8t0nb9%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F8t0nb9%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/7cc6c38d89c8ea946f66e3744632103b/href">https://medium.com/media/7cc6c38d89c8ea946f66e3744632103b/href</a></iframe><p>你不需要特別去做什麼，Section會指定樹狀結構內的 context，因此你可以在裡面的任何地方放進&lt;Heading&gt;，並且得到正確的尺寸。</p><p>Context 會讓你的元件去 “適應它的環境”，並且根據渲染位置有著不同的依據 ( 指的是在哪個 context 裡 )。</p><blockquote>個人覺得官方文件以上這兩段非常饒舌，簡單來說，使用 context 包覆元件，而內部元件會因為所處不同層級，而受到不同的 context 值影響，因為元件它會參照最接近它自己的父層。</blockquote><p>context 的運作就像 CSS 的繼承。<br>例如在&lt;div&gt;指定color: blue，所有在這個&lt;div&gt;內的 DOM 節點，無論層級有多深，都會繼承color: blue，除非你在中間覆寫color: green。<br>同樣地，在 React 裡，唯一覆寫 context 的方式就是將 children 包覆在不同值的 context provider 內。</p><p>在 CSS中，不同的屬性 ( 像是color與background-color) 不會覆蓋彼此，同樣地，不同的 React contexts 也不會覆寫彼此，每一個你用createContext()創造出來的 context 都是彼此分開的，同一個元件使用或 provider 多個不同的 context 是完全沒有問題的。</p><h4>Before you use context</h4><p>context 是一個誘人使用的東西，這意味這它容易被過度使用。<br>需要傳遞 props 到一些較深層級處，不代表就必須使用 context。</p><p>這裡有一些你在使用 context 前可以考慮的選擇：</p><ol><li>從傳遞 props 開始，如果元件並不瑣碎，將多個 props 傳入多個元件並不是不行的，這個方法能讓元件的資料來源清楚明瞭，利於維護。</li><li>提取元件並使用來children傳遞內容，如果有一筆資料通過多層中間元件，而那些中間的元件並不需要這份資料 ( 只是將資料傳到更遠處 )，這通常意味著你忘記提取元件。<br>舉例來說，相較於將postsprop 傳遞給不會直接使用到的元件<br>&lt;Layout posts={posts} /&gt;<br>不如把它直接放在用得到它的地方<br>&lt;Layout&gt;&lt;Posts posts={posts} /&gt;&lt;/Layout&gt;<br>這樣的方法可以減少元件的層級，並直接把資料指定給需要的接收者。</li></ol><p>如果以上這兩種方法都不適合，再考慮使用 context。</p><h4>Use cases for context</h4><p>以下提供一些適合使用 context 的情境：</p><ul><li><strong>Theming</strong>：如果你的 app 可以讓使用者變更它的外觀 ( 像是 dark mode )，你可以在 app 中的最頂層放上 context provider，並且在那些需要轉換外觀的元件上使用 context。</li><li><strong>Current account</strong>：若有多個元件需要知道現在登入的使用者是誰，將它放進 context 可以讓我們更方便於在各個地方讀取資訊，有些 app 會讓你同時操作不同帳號 ( 像是使用不同的身份留下評論 )，在那種情況下，將部分 UI 包覆進不同使用者資訊的 provider，將會是非常方便的。</li><li><strong>Routing</strong>：許多路由方案會在內部使用 context 來維持當前 route，這能讓每個 link “知道” 現在是不是 active 的狀態。</li><li><strong>Managing state</strong>：隨著專案成長，可能會有許多狀態存在於靠近 app 頂層的地方，通常會搭配 reducer 來管理複雜的狀態。<br>( 這部分在下一篇會有詳細的解說 )</li></ul><p>Context 並不會受限於靜態的值，如果你在下一次渲染時傳遞了不同的值，React 將會更新該元件以下的所有內容，這也是為什麼 context 很常與 狀態搭配使用。</p><blockquote>補充：但這也引伸出過於頻繁觸發重新渲染而導致的效能問題。</blockquote><p>一般來說，如果在樹狀結構中，多個位於不同位置的遙遠元件需要同一筆資料，使用 context 將會是一個好方法。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10cace64a054" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【 React 】Reducer 入門]]></title>
            <link>https://medium.com/@jamielolo/react-reducer-%E5%85%A5%E9%96%80-68dec141a6c0?source=rss-9dca7ca3c1ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/68dec141a6c0</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[usereducer]]></category>
            <category><![CDATA[reducer]]></category>
            <dc:creator><![CDATA[Jamie Lo]]></dc:creator>
            <pubDate>Sun, 05 Mar 2023 14:33:12 GMT</pubDate>
            <atom:updated>2023-03-05T14:33:12.311Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*W623C2slJHZVgesQ" /><figcaption>Photo by <a href="https://unsplash.com/@amiion?utm_source=medium&amp;utm_medium=referral">Andra Ion</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>本篇筆記摘錄自官方文件 <a href="https://beta.reactjs.org/learn/extracting-state-logic-into-a-reducer">Extracting State Logic into a Reducer</a></blockquote><p>在<a href="https://medium.com/@jamielolo/react-component-%E5%85%83%E4%BB%B6-4c572fcd4979">元件</a>中透過多個<a href="https://medium.com/@jamielolo/react-%E4%BA%8B%E4%BB%B6%E7%9B%A3%E8%81%BD%E5%99%A8-responding-to-events-fa661a652f8">事件處理器</a>更新多個<a href="https://medium.com/@jamielolo/react-%E7%8B%80%E6%85%8B-state-30a8b791e4bc">狀態</a>可能會發生一些問題。<br>我們可以將所有狀態更新的邏輯寫在元件外面，將它們通通放入一個函式裡，而這個函式就是 reducer。</p><h4>Consolidate state logic with a reducer</h4><p>當元件變得複雜，很難一眼看出是哪一個狀態要用什麼樣的方式更新。<br>以下方的例子來說，TaskApp元件有一個陣列類型的狀態tasks，並且搭配三個不同的事件處理器，分別為 add、remove、edit tasks：</p><p>( 將左側拉桿向右移動，可以看見程式碼的部分，拉開後點擊左上角三條線漢堡圖示可以看見完整檔案，右邊則為輸出結果。 )</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fsleepy-austin-yrv1mz%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fsleepy-austin-yrv1mz%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fyrv1mz%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/763d25868695e67986554b5ece67e77a/href">https://medium.com/media/763d25868695e67986554b5ece67e77a/href</a></iframe><p>這三個事件處理器都是透過呼叫setTasks來更新狀態。<br>隨著元件內容變多，這些狀態設置邏輯會變得到處都是，為了減少複雜度，我們可以將這些狀態邏輯都存到 reducer 裡。</p><p>Reducer 管理狀態的方式與我們先前所學不同，我們會需要透過以下三個步驟來將useState轉為useReducer：</p><p>步驟一：移除設置狀態邏輯，並指派動作 ( dispatching actions )。<br>步驟二：編寫 reducer 函式<br>步驟三：在元件內使用 reducer</p><h4>步驟一：移除設置狀態邏輯，並指派動作。</h4><p>目前的事件處理器是透過狀態設置函式 ( 也就是setTasks )，來指定該做什麼事：</p><pre>function handleAddTask(text) {<br>  setTasks([<br>    ...tasks,<br>    {<br>      id: nextId++,<br>      text: text,<br>      done: false,<br>    },<br>  ]);<br>}<br><br>function handleChangeTask(task) {<br>  setTasks(<br>    tasks.map((t) =&gt; {<br>      if (t.id === task.id) {<br>        return task;<br>      } else {<br>        return t;<br>      }<br>    })<br>  );<br>}<br><br>function handleDeleteTask(taskId) {<br>  setTasks(tasks.filter((t) =&gt; t.id !== taskId));<br>}</pre><p>移除所有狀態設置的邏輯，只需要在事件處理器留下以下內容：</p><ul><li>handleAddTask(text)會在使用者點擊 “Add” 時被呼叫。</li><li>handleChangeTask(text) 會在使用者切換 task 或點擊 “Save” 時被呼叫。</li><li>handleDeleteTask(taskId) 會在使用者點擊 “Delete” 時被呼叫。</li></ul><p>使用 reducer 來管理狀態與直接設置狀態有著些許的不同：<br>設置狀態函式會告訴 React 該做什麼。<br>reduecr 則是透過使用者行為，由事件處理器來指派 “動作” ( 狀態更新邏輯會存在於其他地方 )。</p><p>移除事件監聽器內的setTasks，改為指派 “added / changed / deleted a task” 等動作，能提升使用者行為的描述性。</p><pre>function handleAddTask(text) {<br>  dispatch({<br>    type: &#39;added&#39;,<br>    id: nextId++,<br>    text: text,<br>  });<br>}<br><br>function handleChangeTask(task) {<br>  dispatch({<br>    type: &#39;changed&#39;,<br>    task: task,<br>  });<br>}<br><br>function handleDeleteTask(taskId) {<br>  dispatch({<br>    type: &#39;deleted&#39;,<br>    id: taskId,<br>  });<br>}</pre><p>我們傳入dispatch的物件被稱為 “action”：</p><pre>function handleDeleteTask(taskId) {<br>  dispatch(<br>    // &quot;action&quot; object:<br>    {<br>      type: &#39;deleted&#39;,<br>      id: taskId,<br>    }<br>  );<br>}</pre><p>這是一個常規的 JavaScript 物件，你可以決定要放入哪些內容，但一般來說，至少要包含最小資訊量，也就是發生了什麼事。</p><h4>【 Note 】</h4><p>命名慣例：通常會使用字串類型的type來描述發生什麼事，並將其他資訊放入其他區域，以我們的例子來說，可以命名為added或added_task，簡單來說，就是取名字時要盡量讓它可以一眼看出發生了什麼事。</p><pre>dispatch({<br>  // specific to component<br>  type: &#39;what_happened&#39;,<br>  // other fields go here<br>});</pre><h4>步驟二：編寫 reducer 函式</h4><p>reducer 函式是我們放入狀態邏輯的地方，它會有兩個引數 ( argument )，分別是目前的狀態與 action 物件，此函式將會回傳下一次的狀態，React 則會將狀態設置為 reducer 回傳的內容：</p><pre>function yourReducer(state, action) {<br>  // return next state for React to set<br>}</pre><p>我們可以透過以下三個步驟，將事件處理器中的狀態設置邏輯移到 reducer 函式：</p><ol><li>在第一個引數宣告當前狀態 (tasks)。</li><li>在第二個引數宣告action物件。</li><li>reducer 回傳下一次的狀態 ( React 以此內容來設置狀態)。</li></ol><p>當我們將所有狀態設置邏輯搬到 reducer 時，程式碼會長這樣：</p><pre>function tasksReducer(tasks, action) {<br>  if (action.type === &#39;added&#39;) {<br>    return [<br>      ...tasks,<br>      {<br>        id: action.id,<br>        text: action.text,<br>        done: false,<br>      },<br>    ];<br>  } else if (action.type === &#39;changed&#39;) {<br>    return tasks.map((t) =&gt; {<br>      if (t.id === action.task.id) {<br>        return action.task;<br>      } else {<br>        return t;<br>      }<br>    });<br>  } else if (action.type === &#39;deleted&#39;) {<br>    return tasks.filter((t) =&gt; t.id !== action.id);<br>  } else {<br>    throw Error(&#39;Unknown action: &#39; + action.type);<br>  }<br>}</pre><p>由於 reducer 函式使用狀態 (tasks) 當作引數，因此你可以在元件外部宣告它，這可以減少元件內部的結構層級，增加程式碼的閱讀性。</p><h4>【 Note 】</h4><p>上面的範例是使用 if / else statement 來寫，但大多數人會在 reducer 內使用 switch statement。<br>結果會是一樣的，但是 switch statement 在閱讀上會比較好。<br>轉換後的程式碼如下：</p><pre>function tasksReducer(tasks, action) {<br>  switch (action.type) {<br>    case &#39;added&#39;: {<br>      return [<br>        ...tasks,<br>        {<br>          id: action.id,<br>          text: action.text,<br>          done: false,<br>        },<br>      ];<br>    }<br>    case &#39;changed&#39;: {<br>      return tasks.map((t) =&gt; {<br>        if (t.id === action.task.id) {<br>          return action.task;<br>        } else {<br>          return t;<br>        }<br>      });<br>    }<br>    case &#39;deleted&#39;: {<br>      return tasks.filter((t) =&gt; t.id !== action.id);<br>    }<br>    default: {<br>      throw Error(&#39;Unknown action: &#39; + action.type);<br>    }<br>  }<br>}</pre><p>React 官方推薦將這些case使用{}包覆，這樣在宣告變數時，才不會與其他case發生衝突。</p><p>case必須以return作為結束，如果你忘了return，程式碼會繼續往下一個case執行，這樣將導致錯誤發生。</p><p>如果你還沒有非常習慣 switch statement，使用 if / else statement 也是可以的。</p><h4>【 DEEP DIVE 】</h4><p>雖然 reducers 可以減少 ( reduce ) 元件內的程式碼數量，但實際上的命名是因為reduce()operator，reduce()是陣列的一種方法 ( method )。</p><p>reduce()operator 可以累加陣列中的值：</p><pre>const arr = [1, 2, 3, 4, 5];<br>const sum = arr.reduce(<br>  (result, number) =&gt; result + number<br>); // 1 + 2 + 3 + 4 + 5</pre><p>傳入reduce的函式稱為 “reducer”，它帶有目前的結果與當前項目，並且會回傳下一次的結果。<br>React reducers 運用了相同的概念，它們會獲取目前的狀態與 action，並且回傳下一次的狀態，它們會在狀態累加 actions。</p><p>你可以將initialState與陣列類型的actions傳入reduce()，此方法可以幫我們計算出最後的狀態：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Feloquent-mountain-ogkvy1%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Feloquent-mountain-ogkvy1%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fogkvy1%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/b55adf793ca73d56733eebef7fb37b00/href">https://medium.com/media/b55adf793ca73d56733eebef7fb37b00/href</a></iframe><p>這個範例相似於 React 的運作，通常你不會需要自己去做這件事。</p><h4>步驟三：在元件內使用 reducer</h4><p>最後，你需要將tasksReducers放進元件的 Hook 裡，請確保有正確從 React 匯入useReducer：</p><pre>import {useReducer} from &#39;react&#39;;</pre><p>替換掉原本的useState：</p><pre>const [tasks, setTasks] = useState(initialTasks);</pre><p>改為useReducer：</p><pre>const [tasks, dispatch] = useReducer(tasksReducer, initialTasks);</pre><p>useReducer與 useState非常相似，我們需要傳入初始狀態，useReducer會回傳一個有狀態的值並且使用方法設置狀態 ( 在這個範例裡，指的是 dispatch function )，但它們之間還是有些許差異。</p><p>useReducer有兩個引數 ( arguments)：</p><ol><li>reducer 函式</li><li>初始狀態</li></ol><p>它會回傳：</p><ol><li>有狀態的值</li><li>dispatch function<br>dispatch 為派遣、發送的意思，它會將使用者的動作 ( actions )，發送給 reducer。</li></ol><p>以下為改寫後的程式碼：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fhappy-glade-eueycz%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fhappy-glade-eueycz%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Feueycz%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/1af49b7bfea7b50bf4a7e63c744e5af0/href">https://medium.com/media/1af49b7bfea7b50bf4a7e63c744e5af0/href</a></iframe><p>如果你希望將 reducer 移到其他檔案，也是完全沒有問題的：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fobjective-aj-3uuhkl%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fobjective-aj-3uuhkl%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F3uuhkl%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/22bf63732d7453070e4699949d7eed73/href">https://medium.com/media/22bf63732d7453070e4699949d7eed73/href</a></iframe><p>使用 reducer 將狀態設置邏輯移出元件，將提升元件的閱讀性。<br>現在，事件處理器只會透過 dispatching actions 來告知發生什麼事，要回應的狀態更新則是由 reducer 函式決定。</p><h4>Comparing useState and useReducer</h4><p>Reducers 並非是沒有缺點的，以下列出useState與useReducer的比較：</p><ul><li><strong>Code size</strong>：以前期來說，使用useState可以編寫較少的程式碼，使用useReducer則必須寫出 reducer 函式與 dispatch actions。<br>但是當多個事件處理器修改狀態的方式非常相似時，useReducer會是減少程式碼的一個好方法。</li><li><strong>Readability</strong>：在狀態內容較為單純的情形下，useState的閱讀性是很好的，但當情形變得複雜，它們會膨脹元件內的程式碼，使得閱讀性不佳。<br>在先前的範例中，展示了如何使用useReducer將狀態設置邏輯從事件處理器移出，提升程式碼閱讀性。</li><li><strong>Debugging</strong>：當useState出現 bug 時，很難找出哪邊的狀態不正確，以及為什麼出現 bug。<br>使用useReducer，你可以在 reducer 內加入 console log，以此方法來查看每次狀態更新，以及它為什麼發生 ( 是因為哪個 action )，如果action是正確的，你將會知道問題是出在 reducer 邏輯本身。<br>只是這個方法會需要比使用useState時檢閱更多的程式碼。</li><li><strong>Testing</strong>：reducer 是一個 <a href="https://medium.com/@jamielolo/react-%E4%BF%9D%E6%8C%81%E5%85%83%E4%BB%B6-pure-keeping-components-pure-785bf95cbfe1">pure function</a>，它不會依附於你的元件之上，這也意味著， 你可以分別匯出它們，分別進行測試。<br>儘管一般來說，能夠在愈真實的環境中測試是愈好的，但對於那些複雜的狀態更新邏輯而言，reducer 會根據特定的初始狀態與 action，回傳一個特定的狀態值，這將有助於我們進行<a href="https://zh.wikipedia.org/zh-tw/%E6%96%B7%E8%A8%80_(%E7%A8%8B%E5%BC%8F)">斷言 ( assert )</a>。</li><li><strong>Personal preference</strong>：有些人喜歡 reducers，有些人則不喜歡。<br> 這是沒有關係的，這只是單純的偏好問題，你可以在useState與 useReducer中轉換使用。</li></ul><p>如果你常因錯誤的狀態更新而導致 bug，或是希望程式碼更具有結構性，React 官方推薦使用 reducer。<br>你不必每個地方都使用 reducer，可以自由的搭配使用，在同一個元件裡同時使用useState與useReducer是完全沒有問題的。</p><h4>Writing reducers well</h4><p>編寫 reducers 時，心裡要記住這兩件事：</p><ul><li><strong>Reducers 必須是 pure 的</strong>，與狀態設置函式相同，reducers 會在渲染中運行 ( actions 將會在佇列中等待，直到下一次渲染）。<br>這表示 reducers 必須是 pure 的，同樣的輸入結果，永遠都該得到同樣的輸出，它們不該發送 requests、schedule timeouts，或是使用任何 side effects ( 會影響元件外部任何事的操作 )，它們必須使用非變異 ( without mutations ) 的方式更新物件與陣列類型的狀態。</li><li>每一個 action 描述單一的使用者互動，即使那將導致多筆資料變動。<br>舉例來說，reducer 管理著表單上的五個區塊，當使用者點擊表單上的 “ Reset “ 時，會引發 dispatch 一個reset_form，而不是五個分開的set_field行為。<br>如果你將每一個行為都分開來寫，你必須要非常清楚什麼互動要回傳什麼樣的回應，以什麼樣的順序，描述單一的使用者互動將有助於 debug。</li></ul><h4>Writing concise reducers with Immer</h4><blockquote>如果不清楚 Immer 是什麼，可以參考這篇<a href="https://medium.com/@jamielolo/react-%E6%9B%B4%E6%96%B0%E7%89%A9%E4%BB%B6-state-9e3a051f4561">更新物件類型的 state</a>，官方文件在這篇有稍微介紹了 Immer 是什麼，以及它的使用方法。</blockquote><p>就像我們先前使用 Immer 的方式更新物件與陣列，我們也可以使用 Immer 讓 reducers 更為簡潔，跟之前稍微不同的是，在這邊我們要引入的是useImmerReducer，useImmerReducer讓我們可以使用push或arr[i] = 這種 mutate 的方式來更新狀態：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fwithered-thunder-1kbqy4%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fwithered-thunder-1kbqy4%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F1kbqy4%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/41839a2a57859a421660a9ed60fa97cf/href">https://medium.com/media/41839a2a57859a421660a9ed60fa97cf/href</a></iframe><p>Reducers 必須是 pure 的，所以我們不能使用 mutate 的方式來更新狀態。<br>但是 Immer 提供了一個名為draft的特殊物件，讓我們可以安全的使用mutate 的方式來更新狀態。</p><p>Immer 會創建一個狀態的副本，內容會對應到我們對draft所做的改變，這就是為什麼useImmerReducer可以 mutate reducer 的第一個引數，以及為什麼不需回傳狀態。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68dec141a6c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【 React 】保存與重置狀態]]></title>
            <link>https://medium.com/@jamielolo/react-%E4%BF%9D%E5%AD%98%E8%88%87%E9%87%8D%E7%BD%AE%E7%8B%80%E6%85%8B-de3d38c83661?source=rss-9dca7ca3c1ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/de3d38c83661</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-state]]></category>
            <dc:creator><![CDATA[Jamie Lo]]></dc:creator>
            <pubDate>Sat, 04 Mar 2023 13:51:03 GMT</pubDate>
            <atom:updated>2023-03-04T13:51:03.922Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fE20OadETgceguPE" /><figcaption>Photo by <a href="https://unsplash.com/@sickhews?utm_source=medium&amp;utm_medium=referral">Wes Hicks</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>本篇筆記摘錄自官方文件 <a href="https://beta.reactjs.org/learn/preserving-and-resetting-state">Preserving and Resetting State</a></blockquote><p><a href="https://medium.com/@jamielolo/react-component-%E5%85%83%E4%BB%B6-4c572fcd4979">元件</a>間的<a href="https://medium.com/@jamielolo/react-%E7%8B%80%E6%85%8B-state-30a8b791e4bc">狀態</a>是各自獨立的，React 會依據它們在 UI tree 中的位置，來持續追蹤哪個狀態屬於哪個元件。<br>你可以在重新渲染間控制何時儲存狀態與何時重置狀態。</p><p>這一篇看起來特別長，但大家不要害怕，這篇其實相對容易，只是圖片解說的部分非常多，看起來相較於其他篇會略長一點。</p><h4>The UI tree</h4><p>瀏覽器使用樹狀結構來組裝 UI，<a href="https://developer.mozilla.org/zh-CN/docs/Web/API/Document_Object_Model/Introduction">DOM</a> 代表 HTML 元素、<a href="https://developer.mozilla.org/zh-CN/docs/Web/API/CSS_Object_Model">CSSOM</a> ( CSS Object Model ) 代表 CSS，除此之外還有 Accessibility tree。</p><blockquote>關於 Accessibility tree 可以參考這篇：<a href="https://ithelp.ithome.com.tw/m/articles/10296133">HelloKayac - 什麼是 Accessibility Tree</a></blockquote><p>React 也是使用樹狀結構來管理與模組化 UI。<br>React 透過 <a href="https://medium.com/@jamielolo/react-jsx-%E6%98%AF%E4%BB%80%E9%BA%BC-136d38056fca">JSX</a> 建立 UI trees，React DOM 會更新瀏覽器 DOM 元素，讓結構符合 UI tree。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*jix2I7UCvIMeAZuPjYF6eQ.png" /></figure><p>個人認為官方文件在這邊過於快速帶過，著重於實際操作，並沒有說明底層的原理，老實說這部分我第一次看的時候有看沒有懂：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*P6yA2TOemrrRKO_lOjHsQQ.gif" /></figure><p>如果你跟我一樣，覺得它到底在供殺毀？！<br>真的非常推薦看 Zet 大大的鐵人賽文章，從 Day 04 開始就會有關於渲染機制的介紹，這系列對我的幫助非常大，在這邊推薦給大家。<br>傳送門：<a href="https://ithelp.ithome.com.tw/m/articles/10293802">Zet 鐵人賽系列</a></p><h4>State is tied to a position in the tree</h4><p>當你在元件中設置狀態，你可能會以為狀態 “存活” 在元件中，但狀態其實是由 React 掌控，React 透過元件在 UI tree 中的位置，正確聯繫著每個狀態與其對應的元件。</p><p>下方範例中只有一個&lt;Counter /&gt;JSX 標籤，但它渲染在兩個不同的位置上：</p><p>( 將左側拉桿向右移動，可以看見程式碼的部分，拉開後點擊左上角三條線漢堡圖示可以看見完整檔案，右邊則為輸出結果。 )</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fmusing-mountain-3f7gzd%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fmusing-mountain-3f7gzd%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F3f7gzd%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8eaae95832ab7ca6b0785bb700e4567/href">https://medium.com/media/d8eaae95832ab7ca6b0785bb700e4567/href</a></iframe><p>內容呈現為樹狀結構：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*LcfuCsCuigNsP_QcOHJwWw.png" /></figure><p>嘗試點擊範例中的計數器，可以發現它們是分開計數的。<br>這是因為它們在樹狀結構中各有各的位置，在自己的位置上渲染。<br>了解這個原理將可以幫助我們更加了解 React 的運作方式。</p><p>在 React 中，每個顯示在螢幕上的元件都擁有獨立的狀態。<br>以下方的範例來說，我們在&lt;div&gt;放入兩個Counter元件，它們會有各自的score與hover狀態，你可以透過點擊按鍵與滑動游標來測試效果：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fblazing-darkness-ls5jwy%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fblazing-darkness-ls5jwy%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fls5jwy%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5736ab7fbbae47bf12a65d6f7ceada8/href">https://medium.com/media/f5736ab7fbbae47bf12a65d6f7ceada8/href</a></iframe><p>如測試結果所見，只有被點擊或放上游標的那個元件的狀態會被更新：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*bxa9Hy1EbZ2U95AgQkkpvw.png" /></figure><p>React 會持續地幫我們保存狀態，直到我們移除這個元件。</p><p>請試著點擊下方的計數器，接著點選 checkbox 移除第二個&lt;Counter /&gt;元件，結著再點選一次 checkbox，觀察計數器的內容：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fpractical-bas-o5qxmg%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fpractical-bas-o5qxmg%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fo5qxmg%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/97caab8f3b2c699c8ca1ce93194d2637/href">https://medium.com/media/97caab8f3b2c699c8ca1ce93194d2637/href</a></iframe><p>當你停止渲染第二個&lt;Counter /&gt;時，原本的狀態內容完全消失了。<br>這是因為當元件被移除時，它的狀態也會同時被摧毀。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*1QZLndvmv07xPOdZRhjoEQ.png" /></figure><p>當你勾選 “Render the second counter” 時，第二個Counter元件與它的變數將會重新初始化 (score = 0)，並且被加入 DOM。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*-w6T61EJ3IiFfJqltxOUYg.png" /></figure><p>當元件保持在同一個位置渲染的時候，React 會持續保存它的狀態，一旦元件遭到移除或是換成其他元件在那個位置渲染，React 就會移除它的狀態。</p><h4>Same component at the same position preserves state</h4><p>下方這個範例裡有兩個不同的&lt;Counter /&gt;標籤：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fimmutable-forest-q77znv%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fimmutable-forest-q77znv%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fq77znv%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/00b8776d94572a81e7eccbe01c0614f7/href">https://medium.com/media/00b8776d94572a81e7eccbe01c0614f7/href</a></iframe><p>試著切換 checkbox 會發現狀態並沒有重置。<br>這是因為不管isFancy是true還是false，App元件 return 的結構都是一樣的，有一個div，然後它的子層內容第一項是&lt;Counter /&gt;：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*P27dbqgMMYAF7qhCBBXTEg.png" /></figure><p>只要是同一個元件且位於相同的位置，React 就會認定它們是一樣的。</p><h4>【 Pitfall 】</h4><p>請注意，這邊提到的位置都是在指 UI tree 的位置，並非 JSX 的位置。</p><p>下方刻意對程式碼做了修改，改為使用 if statement 來判斷該渲染哪種效果，從程式碼可以看出兩個&lt;Counter /&gt;在 JSX 中的位置是完全不一樣的：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fweathered-monad-omf2o9%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fweathered-monad-omf2o9%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fomf2o9%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f2fd4815fd42f6a1607fec34b94f366/href">https://medium.com/media/8f2fd4815fd42f6a1607fec34b94f366/href</a></iframe><p>你可能預期切換 checkbox 後狀態會重置，但這並沒有發生。<br>這是因為兩個&lt;Counter /&gt;都是被渲染在同樣的位置上，React 不會知道我們在函式內加了條件式判斷，它只會 “看見” 你 return 的 tree。</p><p>在這兩種情形裡，App元件都是 return 相同的結構，也就是div子層內容第一項都是&lt;Counter /&gt;，這就是為什麼 React 會將它們視為同一個&lt;Counter /&gt;的原因。</p><p>你可以把這個觀念想成是：它們擁有相同的地址，它們都是根元件內的第一個子層，以及第一個子層中的第一個子層。<br>( 沒有錯，繞口令時間又到了！)</p><p>React 不會去管你的邏輯結構是什麼，它只會去比較前一次渲染與下一次渲染的位置。</p><h4>Different components at the same position reset state</h4><p>接下來，我們換個範例，請先點選計數器，然後切換 checkbox 狀態：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fzealous-mountain-ti7i1q%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fzealous-mountain-ti7i1q%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fti7i1q%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/da60ac9b6a4ca0b446bcded0c4a74e6c/href">https://medium.com/media/da60ac9b6a4ca0b446bcded0c4a74e6c/href</a></iframe><p>你可能會覺得，剛剛不是說在同一個位置的話，狀態就不會重置嗎？<br>為什麼重置了呢？</p><p>雖然的確是渲染在同一個結構位置上，但是它們是兩個不同的元件。<br>仔細看看程式碼，當我們切換 checkbox 時，其實是在切換&lt;p&gt;與&lt;Counter /&gt;，所以狀態也會隨著元件移除而被摧毀。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*xZjTtCJbMbrXLuf9WQ7HVQ.png" /></figure><p>再換一個範例，先從程式碼來猜猜看這次狀態會不會被重置：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fkeen-tharp-zo8qbe%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fkeen-tharp-zo8qbe%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fzo8qbe%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b80dc407a35a5d9795c5c71f64c9618/href">https://medium.com/media/4b80dc407a35a5d9795c5c71f64c9618/href</a></iframe><p>答案是：會！</p><p>雖然在這個範例裡，我們渲染的是同一個元件，但是它們的結構並不相同，一個是包在div裡，一個則是包在section裡。</p><p>舉例來說，當div從 DOM 移除的時候，div內部的所有子元素也會跟著被移除，包含Counter 與它的狀態。</p><p>section切換為div時：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*eLwtyK6AaLojo8nAhdw0lA.png" /></figure><p>div切換為section時：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*2LH8dXNidNE4P2Mmvg5jrA.png" /></figure><p>來總結一下目前為止提到的觀念：</p><p>如果你希望在重新渲染之間保持狀態的儲存，上一次渲染與下一次渲染時的 UI tree 結構必須相同。<br>若結構不同，當元件被移除時，React 就會摧毀它所儲存的狀態。</p><h4>【 Pitfall 】</h4><p>請試著在輸入框輸入內容，輸入完後點擊右方的計數器：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fsharp-nash-48dzyh%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fsharp-nash-48dzyh%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F48dzyh%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3e08fb77e777239aeef58c9abc07679/href">https://medium.com/media/c3e08fb77e777239aeef58c9abc07679/href</a></iframe><p>先說結論：以上範例足夠說明，為什麼我們不應該用巢狀結構來定義元件。</p><p>每一次點擊計數器時，輸入框原本的內容都會消失，這是因為每當MyComponent發生渲染，就會重新建立一個MyTextField函式。<br>等於我們在同一個位置渲染了不同的元件，所以 React 會重置它以下的所有狀態 ( 這邊的 “以下” 指的是 UI tree 結構)，這將會導致 bug 的發生。</p><p>為了避免這樣的問題產生，請永遠將元件宣告在最高階級的位置，而不是使用巢狀結構來宣告。</p><h4>Resetting state at the same position</h4><p>React 的預設行為：當元件處於同一個位置時，便保存它的狀態 。<br>但如果我們就是想要重置狀態，又該怎麼做呢？</p><p>目前下方範例中，兩位玩家的分數並沒有被分開計算，試著想想，該怎麼做才能在切換玩家時重置他們的分數：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Ffestive-swartz-huufo3%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Ffestive-swartz-huufo3%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fhuufo3%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a2a4fdd74c498f62cfda1a7e1a5f032/href">https://medium.com/media/0a2a4fdd74c498f62cfda1a7e1a5f032/href</a></iframe><p>目前狀態持續保存是因為我們在同一個位置渲染Counter元件，React 會將它們視為同一個Counter，只是personprop 被改變了而已。</p><p>以下兩種方式可以在切換間重置狀態：</p><p>方法一：在不同的位置渲染元件。</p><p>方法二：賦予元件key，讓它們有明確的身份。</p><h4>方法一：在不同的位置渲染元件</h4><p>如果希望兩個Counter可以各自獨立，我們可以將它們渲染在不同的位置：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Faffectionate-pine-hp1vxq%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Faffectionate-pine-hp1vxq%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fhp1vxq%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a959f2ac85b86fc38fecd0037f4d4d4/href">https://medium.com/media/3a959f2ac85b86fc38fecd0037f4d4d4/href</a></iframe><ul><li>最初，isPlayerA為true，會保有第一個位置的Counter及其狀態，第二個位置則是空的。</li><li>當點擊 “Next player” 按鍵，第一個位置的內容會被清除，第二個位置則會有Counter元件及其狀態。</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*mR50ZUTjkE7uBgJ1PeamGQ.png" /></figure><p>每個Counter元件從 DOM 移除時，它所保有的狀態也會跟著被摧毀，這也是為什麼我們點擊按鍵時能夠重置狀態。</p><p>當需要獨立的元件並不多時，這會是一個很方便的方法，就像這個例子，我們只有兩個需要獨立的元件，因此將它們分開來寫並不麻煩。</p><h4>方法二：賦予元件 key，讓它們有明確的身份。</h4><p>如果你還不太了解 React 裡的key是什麼，可以參考這篇 <a href="https://medium.com/@jamielolo/react-%E6%B8%B2%E6%9F%93%E5%88%97%E8%A1%A8-rendering-lists-6a9838b44faa">渲染列表 ( Rendering Lists )</a>。</p><p>這是另一個更為通用的重置元件狀態方法。<br>key不僅僅可以拿來設置列表，也可以讓 React 區分出不同的元件。<br>React 預設以順序來辨別元件，像是父層裡的第一個Counter、父層裡的第二個Counter。<br>key會讓這些元件不僅僅是第一個Counter、第二個Counter，而是特定的Counter。<br>舉例來說：Taylor&#39;s counter。</p><p>透過設置key，即便元件位於相同的位置，它們也不會共享彼此的狀態：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fkeen-mendeleev-cc3i15%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fkeen-mendeleev-cc3i15%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fcc3i15%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd25f64d93c7822ac6a482204eddf6ea/href">https://medium.com/media/bd25f64d93c7822ac6a482204eddf6ea/href</a></iframe><p>由於將它們設置為不同的key，因此在切換時不會保存狀態：</p><pre>{isPlayerA ? (<br>  &lt;Counter key=&quot;Taylor&quot; person=&quot;Taylor&quot; /&gt;<br>) : (<br>  &lt;Counter key=&quot;Sarah&quot; person=&quot;Sarah&quot; /&gt;<br>)}</pre><p>設置key可以讓我們告訴 React，請使用key來當作位置的一部分，而不是只使用順序來辨別它們。</p><p>這也是為什麼我們在同個位置渲染它們，卻能被視為兩個不同的Counter。</p><p><strong>注意</strong>：這個key並非在全域中獨特的值，單純只是用來區分父層內的元件。</p><h4>Resetting a form with a key</h4><p>用key來重置表格狀態是一個特別有用的方式。</p><p>在這個範例裡，&lt;Chat&gt;元件內有個 text 狀態，用來保存輸入框內容：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Ffocused-maxwell-qssvz0%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Ffocused-maxwell-qssvz0%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fqssvz0%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/48560785f3aa4b9e699f9888cd01dff6/href">https://medium.com/media/48560785f3aa4b9e699f9888cd01dff6/href</a></iframe><p>試著在輸入框輸入內容，接著切換左方的姓名，你會發現輸入框的內容並沒有被重置，這是因為&lt;Chat&gt;在相同的位置渲染。</p><p>這樣的運作是不能在聊天 app 中出現的，因為你很有可能一不小心就把同樣的訊息傳給另一個人，我們可以用key來修正這個問題：</p><pre>&lt;Chat key={to.id} contact={to} /&gt;</pre><p>這可以確保在選擇不同接收者時，Chat元件會被重新創建，包含在它以下的所有結構 ( 這邊說的是 UI tree )，React 也會重新創建 DOM 元素，而不是重複使用它們。</p><p>經過修正後的版本，每次切換人名時，輸入框的狀態都會被重置：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fjovial-pine-pj2njy%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fjovial-pine-pj2njy%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fpj2njy%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/72b80d1824d4e1b8a97800a7cc955019/href">https://medium.com/media/72b80d1824d4e1b8a97800a7cc955019/href</a></iframe><p>【 DEEP DIVE 】</p><p>在真正的聊天軟體中，當我們選擇先前聊過天的同一個接收者時，我們可能會希望能夠恢復輸入框的內容，以下有一些方法可以讓狀態保持：</p><ul><li>可以渲染所有的聊天內容，而非只有當前的這個。<br>然後使用 CSS 來隱藏其他的部分，Chat不會從 tree 中被移除，所以它們的本地狀態將可以被保存。<br>這個方法適合使用在簡單的 UI 上，如果要隱藏的 tree 過大，且包含很多 DOＭ 節點時，將會讓速度變得緩慢。</li><li><a href="https://medium.com/@jamielolo/react-%E5%85%83%E4%BB%B6%E9%96%93%E7%9A%84%E7%8B%80%E6%85%8B%E5%88%86%E4%BA%AB-7f94b9b02139"><strong>lift state up</strong></a><strong> </strong>至父元件，將資訊保存在父元件。<br>使用這個方法時，子元件被移除是沒有關係的，因為我們的資訊是存在父元件，這是最常用的解法。</li><li>可以搭配 React 以外的方法使用。<br>舉例：我們可能會需要有草稿的功能，在我們不小心關掉頁面時，還能保有先前的訊息。<br>為了達成這個功能，你可以將草稿存放在localStorage，並且以localStorage內的資料來當作狀態的初始值。</li></ul><p>不管使用以上哪個方法，不同接收者的訊息一樣是區分開的，所以在這個例子裡，在&lt;Chat&gt;上設置key也是非常合理的。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de3d38c83661" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【 React 】元件間的狀態分享]]></title>
            <link>https://medium.com/@jamielolo/react-%E5%85%83%E4%BB%B6%E9%96%93%E7%9A%84%E7%8B%80%E6%85%8B%E5%88%86%E4%BA%AB-7f94b9b02139?source=rss-9dca7ca3c1ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f94b9b02139</guid>
            <category><![CDATA[react-state]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Jamie Lo]]></dc:creator>
            <pubDate>Thu, 02 Mar 2023 10:48:49 GMT</pubDate>
            <atom:updated>2023-03-02T10:48:49.154Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ASQ44eOYPMYVlPnA" /><figcaption>Photo by <a href="https://unsplash.com/@louishansel?utm_source=medium&amp;utm_medium=referral">Louis Hansel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>本篇筆記摘錄自官方文件 <a href="https://beta.reactjs.org/learn/sharing-state-between-components">Sharing State Between Components</a></blockquote><p>如果你希望兩個<a href="https://medium.com/@jamielolo/react-component-%E5%85%83%E4%BB%B6-4c572fcd4979">元件</a>內的狀態可以同時改變，可以將狀態從兩個元件內移除，改為將狀態變數放在最接近它們的共同父層，接著以 <a href="https://medium.com/@jamielolo/react-%E5%85%83%E4%BB%B6%E8%88%87-props-3b1200cec14d">props</a> 的方式傳入，這便是有名的 <strong>lifting state up</strong>。</p><h4>Lifting state up by example</h4><p>在下方這個範例中，父元件Accordion渲染了兩個分開的Panel元件。</p><p>兩個Panel元件裡各自有isActive狀態變數，用來決定內容是否顯示。<br>請試著點擊輸出畫面中的 Show 按鍵：</p><p>( 將左側拉桿向右移動，可以看見程式碼的部分，拉開後點擊左上角三條線漢堡圖示可以看見完整檔案，右邊則為輸出結果。 )</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fagitated-rubin-60d400%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fagitated-rubin-60d400%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F60d400%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd78d25e8ab9358210442a6307ac2138/href">https://medium.com/media/fd78d25e8ab9358210442a6307ac2138/href</a></iframe><p>點擊其中一個按鍵，並不會影響到另一邊的結果，它們是各自獨立的。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*ZAFrDIJCZkdAAdf5OiyNnA.png" /></figure><p>進階版：點擊按鍵時，顯示該區域的內容，另一個區域的內容則須隱藏。</p><p>我們可以透過以下三個步驟達成這個效果：</p><ol><li>移除子元件中的狀態。</li><li>透過父元件將資料以 <a href="https://zh.wikipedia.org/zh-tw/%E5%AF%AB%E6%AD%BB">hardcode</a> 的方式傳遞給子元件。</li><li>將狀態加至共同父元件，透過父元件將狀態與事件處理器傳給子元件。</li></ol><h4>Step 1: Remove state from the child components</h4><p>將Panel裡isActive的控制權交給它們的父元件，這代表著父元件會透過傳遞 prop 的方式，將isActive傳遞給Panel。</p><p>將以下程式碼從Panel移除：</p><pre>const [isActive, setIsActive] = useState(false);</pre><p>改以 props 的方式引入：</p><pre>function Panel({ title, children, isActive }) {</pre><h4>Step 2: Pass hardcoded data from the common parent</h4><p>狀態必須抬升至最接近的共同父元件，在這個範例裡，是Accordion元件。</p><p>透過Accordion元件將isActive的值以 <a href="https://zh.wikipedia.org/zh-tw/%E5%AF%AB%E6%AD%BB">hardcode</a> 的方式傳遞給Panel：<br>( 像是傳入true)</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fclever-james-g47pds%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fclever-james-g47pds%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fg47pds%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/db62cdd9108066b6f310fe282c21dc54/href">https://medium.com/media/db62cdd9108066b6f310fe282c21dc54/href</a></iframe><p>試著將isActive的值改為false，並觀察右側顯示畫面的變動。</p><h4>Step 3: Add state to the common parent</h4><p>通常狀態抬升後，會改變原本的狀態儲存方式。</p><p>以這個範例來說，同一個時間裡只會有一個Panel為 active，這意味著Accordion元件必須追蹤目前哪一個Panel處於 active 的狀態。<br>相較於原本的boolean，使用索引值來判斷會是一個比較合適的方法：</p><pre>const [activeIndex, setActiveIndex] = useState(0);</pre><p>當isActive為0，第一個Panel為 active，當isActive為1，第二個Panel為 active。</p><p>點擊 Show 按鍵時，改變Accordion裡的 active 索引值。<br>不能直接在Panel設置activeIndex，如果想要間接的改變狀態，父元件必須以 prop 的方式將事件處理器傳入子元件：</p><pre>&lt;&gt;<br>  &lt;Panel<br>    isActive={activeIndex === 0}<br>    onShow={() =&gt; setActiveIndex(0)}<br>  &gt;<br>    ...<br>  &lt;/Panel&gt;<br>  &lt;Panel<br>    isActive={activeIndex === 1}<br>    onShow={() =&gt; setActiveIndex(1)}<br>  &gt;<br>    ...<br>  &lt;/Panel&gt;<br>&lt;/&gt;</pre><p>在Panel裡的&lt;button&gt; 會在點擊時觸發onShow：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fhopeful-raman-1jkdgm%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fhopeful-raman-1jkdgm%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F1jkdgm%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/672f9b7c408d0c86c1cfc8ff41672cd5/href">https://medium.com/media/672f9b7c408d0c86c1cfc8ff41672cd5/href</a></iframe><p>現在我們已經完成了所有抬升狀態的動作。<br>選擇使用索引值而不是 “is shown” 可以確保一次只會有一個Panel為 active。<br>而將事件處理器傳入子元件，可以讓子元件改變父元件的狀態。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*QVK3lgYMvR6GJGFhPhD6wA.png" /></figure><h4>【 DEEP DIVE 】</h4><p><strong>Controlled and uncontrolled components</strong></p><p>這個觀念算是蠻常在面試考古題中看到的問題。</p><p>將某些本地狀態稱為 “uncontrolled” 是一個常見的情形。<br>舉例來說，最一開始的範例裡，有著isActive狀態變數的Panel元件就是一個不可控元件，因為父元件並沒有辦法去影響Panel的 active 狀態。</p><p>相對的，如果是透過 props 來操縱資料，而不是使用本地狀態，父元件可以完全掌控子元件的行為，就可以稱之為可控元件。</p><p>雖然本地狀態可以使用較少的配置，在使用上比較方便。<br>但如果今天需要元件間互相配合，使用可控元件將會使運作更加彈性。</p><p>在實作上，可控與不可控並非是嚴格區分的，通常元件會同時有本地狀態與 props，但理解這個原理，可以讓我們更清楚元件的設計，以及元件提供了哪些功能。</p><p>在編寫元件時，可以試著去想哪些資訊應該要是可控的 ( 透過 props )，哪些資料是不可控的 ( 透過狀態 )，不管是哪一種，你都可以隨著自己的心意在後續重構它們。</p><h4>A single source of truth for each state</h4><p>在 React 裡，許多元件都會擁有它們自己的狀態，有些狀態可能會存在於較底層元件內 ( 這邊的底層指的是元件樹結構的底層 )，像是input。<br>有些狀態會存在於較接近頂層的位置，舉一個常見的例子，client 端的路由函式庫將當下路由儲存在狀態裡，並且以 props 的方式傳遞。</p><p>對於每一個獨特的狀態，我們會需要去選擇該讓哪個元件 “擁有” 它，也就是將狀態定義在哪個元件裡，這個原則便是著名的 “single source of truth”。</p><p>這句話的意思並非是指所有狀態存在於同一個位置。<br>它的意思是：每一個狀態都會有特定的元件來負責保存資料，如果你希望元件間的資料能夠交流，你不應該使用複製的方式來分享，而是將狀態抬升至最靠近它們的共同父元件，並由父元件透過 props 將資料傳給子元件。</p><p>在開發的過程中，我們可能會移動狀態的位置，不管是抬升至父元件還是移到子元件，以找尋最適合它們的位置，這是沒有關係的，因為這也是一種練習的過程。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f94b9b02139" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【 React 】狀態結構 ( State Structure )]]></title>
            <link>https://medium.com/@jamielolo/react-%E7%8B%80%E6%85%8B%E7%B5%90%E6%A7%8B-state-structure-7c10f38ff707?source=rss-9dca7ca3c1ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c10f38ff707</guid>
            <category><![CDATA[react-state]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Jamie Lo]]></dc:creator>
            <pubDate>Wed, 01 Mar 2023 18:13:36 GMT</pubDate>
            <atom:updated>2023-03-02T01:56:06.545Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CNwhX7G3fQIXxd4-" /><figcaption>Photo by <a href="https://unsplash.com/@rgaleriacom?utm_source=medium&amp;utm_medium=referral">Ricardo Gomez Angel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>本篇筆記摘錄自官方文件 <a href="https://beta.reactjs.org/learn/choosing-the-state-structure">Choosing the State Structure</a></blockquote><p>好的狀態結構可以使修改與 debug 變得更加容易。</p><h4>Principles for structuring state</h4><p>在<a href="https://medium.com/@jamielolo/react-component-%E5%85%83%E4%BB%B6-4c572fcd4979">元件</a>內編寫<a href="https://medium.com/@jamielolo/react-%E7%8B%80%E6%85%8B-state-30a8b791e4bc">狀態</a>變數時，我們會需要思考要定義多少個狀態變數，以及要存入的資料樣貌，雖然較不好的狀態結構也能成功運行，但 React 官方提供了一些原則給我們，讓我們在編寫時有更好的選擇：</p><ol><li><strong>Group related state.</strong><br>如果總是同時更新兩個或兩個以上的狀態，可以考慮將它們合併成一個狀態變數。</li><li><strong>Avoid contradictions in state.</strong><br>當狀態被拆為多個部份，彼此之間可能會產生矛盾，請避免此情況。</li><li><strong>Avoid redundant state</strong>.<br>如果需要的資訊可以從 <a href="https://medium.com/@jamielolo/react-%E5%85%83%E4%BB%B6%E8%88%87-props-3b1200cec14d">props</a> 或已存在狀態變數中取得，請勿再為資訊建立新的狀態變數，以避免產生多餘的狀態。</li><li><strong>Avoid duplication in state.<br></strong>當相同的資訊複製於多個狀態間，或是在多層的物件結構中，將難以保持它們的同步，應盡可能地減少複製。</li><li><strong>Avoid deeply nested state.<br></strong>過於多層的狀態結構將不易於更新，盡可能以平坦的方式建構狀態。</li></ol><p>目的：在不導致錯誤發生的情況下，讓狀態能夠更容易的被更新。<br>移除多餘與複製的資訊，可以確保所有資訊同步。</p><p>官方引用了愛因斯坦的名言：<br>Make everything as simple as possible, but not simpler.</p><p>並將它套用在狀態結構的原則上：<br>Make your state as simple as it can be — but no simpler.</p><p>接下來，我們將依序將上面的原則套進實際的範例。</p><h4>Group related state</h4><p>在某些時候，我們可能會不確定該分開儲存狀態，還是將它們存成同一個。</p><p>請先看看下面兩種寫法：</p><pre>const [x, setX] = useState(0);<br>const [y, setY] = useState(0);</pre><pre>const [position, setPosition] = useState({ x: 0, y: 0 });</pre><p>以上兩種寫法其實都是可以的，但如果兩個狀態變數常常需要同時更新，就會建議將它們合併成一個 ( 範例 2 )，這樣才不會在更新的時候忘記保持它們的同步。</p><p>就像下方的這個範例一樣，輸出畫面的紅點會跟著游標移動，如果分開儲存狀態，遺忘更新 x 軸或 y 軸，就沒辦法達成想要的效果：</p><p>( 將左側拉桿向右移動，可以看見程式碼的部分，拉開後點擊左上角三條線漢堡圖示可以看見完整檔案，右邊則為輸出結果。 )</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fepic-johnson-13x7mv%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=http%3A%2F%2Fcodesandbox.io%2Fembed%2Fepic-johnson-13x7mv%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F13x7mv%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/32c88d42e22a4b56d402672a246e3f51/href">https://medium.com/media/32c88d42e22a4b56d402672a246e3f51/href</a></iframe><p>當你不知道你需要儲存多少資料時，也很適合將它們存進物件或陣列。<br>例如：使用者可以客制化區塊的表格。</p><h4>【 Pitfall 】</h4><p>如果你的狀態變數是一個物件，請記得要先複製物件後再更新。<br>以上面的這個例子來說，我們不能使用setPosition({ x: 100 })直接更新，這個寫法將不包含y屬性及其內容。<br>如果想要單獨更新x，必須寫為setPosition({ ...position, x: 100 })，或是將狀態變數拆成兩個，一個負責x、一個負責y。<br>像是這樣：setX(100) 。</p><blockquote>更詳細的物件狀態變數更新介紹，可以參考<a href="https://medium.com/@jamielolo/react-%E6%9B%B4%E6%96%B0%E7%89%A9%E4%BB%B6-state-9e3a051f4561">更新物件類型的 state</a>。</blockquote><h4>Avoid contradictions in state</h4><p>下方範例為飯店的回饋表單，具有isSending與isSent兩個狀態變數：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fheuristic-hawking-pkwdmp%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fheuristic-hawking-pkwdmp%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fpkwdmp%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/50146a1259d9d1b9eebac9d89aa1ba07/href">https://medium.com/media/50146a1259d9d1b9eebac9d89aa1ba07/href</a></iframe><p>雖然功能能夠正常運作，但這樣的做法會有一些問題。<br>舉例來說，如果今天忘了同時呼叫isSending與isSent，可能會發生isSending與isSent同時為true的情形。<br>當元件變得更加複雜時，更容易出現無法預期的錯誤。</p><p>由於它們永遠都不該同時為true，將它們放在同一個狀態變數裡將會是一個比較好的做法。</p><p>下方為修正後的範例，將typing ( 初始值 )、sending、sent三種狀情形存在同一個狀態變數 (status) 裡：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Flaughing-mendel-ue8v0i%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Flaughing-mendel-ue8v0i%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fue8v0i%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdda89542930f774fe52d5c4e62ab048/href">https://medium.com/media/cdda89542930f774fe52d5c4e62ab048/href</a></iframe><p>你依然可以為了提升閱讀性而宣告一些變數，但它們並非狀態變數，因此不必擔心它們彼此間會有同步的問題：</p><pre>const isSending = status === &#39;sending&#39;;<br>const isSent = status === &#39;sent&#39;;</pre><h4>Avoid redundant state</h4><p>如果需要的資訊可以從 props 或已存在狀態變數中取得，請勿再為資訊建立新的狀態變數，以避免產生多餘的狀態。</p><p>下方是一個可以正常運作的表單，看看程式碼，是不是有多餘的狀態變數呢？</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fadoring-andras-3w14pb%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fadoring-andras-3w14pb%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F3w14pb%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/26e198eeba236651d401b8ffaafa2735/href">https://medium.com/media/26e198eeba236651d401b8ffaafa2735/href</a></iframe><p>這個表單有三個狀態變數：firstName、lastName、fullName。<br>fullName為多餘的狀態變數，因為可以透過firstName與lastName取得。<br>我們可以將它修正為這樣：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fbold-mountain-b8ive6%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fbold-mountain-b8ive6%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fb8ive6%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4a3d9a0dac9f4d33c6e78cc350860bf/href">https://medium.com/media/c4a3d9a0dac9f4d33c6e78cc350860bf/href</a></iframe><p>修正後的fullName並非狀態變數，而是透過計算取得：</p><pre>const fullName = firstName + &#39; &#39; + lastName;</pre><p>不需要對fullName使用事件處理器來更新，因為不管是firstName或是lastName更新都會觸發重新渲染，都能得到正確的結果。</p><h4>【 DEEP DIVE 】</h4><p>另一種常見的多餘變數如下：</p><pre>function Message({ messageColor }) {<br>  const [color, setColor] = useState(messageColor);</pre><p>color的初始值為傳入的 prop messageColor，如果父層傳入不同的值，並不會觸發color的更新，因為狀態只會在首次渲染時使用初始值。</p><p>我們應該要直接使用messageColor，才能保持與 prop 的同步，像是這樣：</p><pre>function Message({ messageColor }) {<br>  const color = messageColor;</pre><p>一開始的方法則是適合用在忽略特定 prop 的更新，以命名慣例來說，應該要在 prop 的名稱加上initial或是default來區分：</p><pre>function Message({ initialColor }) {<br>  // The `color` state variable holds the *first* value of `initialColor`.<br>  // Further changes to the `initialColor` prop are ignored.<br>  const [color, setColor] = useState(initialColor);</pre><h4>Avoid duplication in state</h4><p>下方範例為一個具有互動性的表單，你可以透過點擊輸出結果的 Choose 按鍵來更換選項：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fgracious-butterfly-3ll5lu%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fgracious-butterfly-3ll5lu%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F3ll5lu%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e6110ac4af42f1b60bdf190729597d1/href">https://medium.com/media/1e6110ac4af42f1b60bdf190729597d1/href</a></iframe><p>上方程式碼將選擇的項目存放在selectedItem裡，但這並不是個好方法。<br>selectedItem的內容與items是一樣的，這意味著同樣的資訊被複製成兩份。</p><p>我們用下方的範例來解釋這個方法為什麼不好：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fpedantic-hill-bnggym%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fpedantic-hill-bnggym%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2ca29cd03b99ae698081062af6302ca/href">https://medium.com/media/a2ca29cd03b99ae698081062af6302ca/href</a></iframe><p>請先點擊其中一個 Choose 按鈕，接著在該輸入框輸入文字，輸入框的內容成功更新，但底部的訊息並沒有跟著更新。<br>這是因為我們複製了狀態變數，卻忘了更新selectedItem。</p><p>雖然可以透過更新selectedItem來修正這個問題，但移除複製的狀態變數是更加簡便且更好的辦法。</p><p>下方修正的範例將selectedItem改為selectedId，透過搜尋items陣列裡的 id，來達成我們想要的效果，此方法刪除了複製的狀態變數，只留下了必要的狀態變數：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fcool-sunset-5b25vk%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fcool-sunset-5b25vk%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F5b25vk%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/cabfd17cecaa1e0e06b5f0eff941edb9/href">https://medium.com/media/cabfd17cecaa1e0e06b5f0eff941edb9/href</a></iframe><p>由於setItems觸發重新渲染後，items.find(...) 會透過 id 找到對應項目更新後的 title，因此能夠做出上述的效果。</p><h4>Avoid deeply nested state</h4><p>想像你正在進行一個環遊宇宙的旅行，旅途中必須記錄所有去過的地方，可能一不小心就會成這樣的巢狀結構：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fzen-forest-1n8twj%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fzen-forest-1n8twj%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F1n8twj%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f0875b5e109693989c5a1802a11f601/href">https://medium.com/media/9f0875b5e109693989c5a1802a11f601/href</a></iframe><p>如果想要加上一顆按鈕，用來刪除已經去過的地方，該怎麼做呢？</p><p>更新巢狀結構的狀態變數，由於 reference 參照的關係，會需要複製裡面的物件，刪除一個深層巢狀結構內的資料，會需要複製一連串的物件來達成，這將造成程式碼非常冗長。</p><p>如果巢狀狀態變數不易更新，請試著把它變得 “平坦”。<br>以這個範例來說，與其在每個childPlaces裡面放入各種巢狀資料，不如直接給它們 ID，以 ID 的方式來獲取資訊。</p><p>透過這個方式，狀態變數變得 “平坦”，這個行為被稱為 “normalized”：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fquirky-paper-cdkq4k%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fquirky-paper-cdkq4k%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fcdkq4k%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/8289d7c4e67391c2403722d194f5b068/href">https://medium.com/media/8289d7c4e67391c2403722d194f5b068/href</a></iframe><p>現在，要達成刪除地點的效果，我們只需要更新兩層狀態變數：</p><ul><li>將小區域的 ID 從它父區域裡的childIds移除。<br>( 例如今天已經去過地球上的非洲，我們就要將非洲的 ID 從地球的childIds中移除。)</li><li>更新根物件 ( root )，它的內容必須是更新版本的父區域內容。</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fjovial-resonance-qf818i%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fjovial-resonance-qf818i%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fqf818i%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e8c2295196cf1597429a7ba6c3b9716/href">https://medium.com/media/3e8c2295196cf1597429a7ba6c3b9716/href</a></iframe><p>雖然可以依據喜好使用巢狀結構來定義狀態變數，但盡可能的保持結構 “平坦”，可以使狀態更容易被更新，並且確保不會有複製內容的狀況出現。</p><h4>【 DEEP DIVE 】</h4><p>最近意外發現 React 官方文件很愛使用 Immer 範例來做結尾。</p><p>以下情境為：從根物件刪除整個父區域及其內容，來達成記憶體的優化。<br>此範例使用 Immer 來達成效果，如果不知道什麼是 Immer 的話，可以參考 <a href="https://medium.com/@jamielolo/react-%E6%9B%B4%E6%96%B0%E7%89%A9%E4%BB%B6-state-9e3a051f4561">更新物件類型的 state</a> 的最後一段。</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fquizzical-noyce-zim79i%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fquizzical-noyce-zim79i%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fzim79i%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/9cba14a5d561a4aa43adb8e8cf3c73bd/href">https://medium.com/media/9cba14a5d561a4aa43adb8e8cf3c73bd/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c10f38ff707" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【 React 】state、input 與 UI 間的關係]]></title>
            <link>https://medium.com/@jamielolo/react-state-input-%E8%88%87-ui-%E9%96%93%E7%9A%84%E9%97%9C%E4%BF%82-ad06f9e7798c?source=rss-9dca7ca3c1ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad06f9e7798c</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-state]]></category>
            <dc:creator><![CDATA[Jamie Lo]]></dc:creator>
            <pubDate>Sat, 25 Feb 2023 15:30:33 GMT</pubDate>
            <atom:updated>2023-02-25T15:38:02.932Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qQ6F6vIB8wQ9-9R5" /><figcaption>Photo by <a href="https://unsplash.com/ko/@juvnsky?utm_source=medium&amp;utm_medium=referral">Anton Maksimov 5642.su</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>本篇筆記摘錄自官方文件 <a href="https://beta.reactjs.org/learn/reacting-to-input-with-state">Reacting to Input with State</a></blockquote><p>React 使用陳述式 (declarative) 來操縱 UI。<br>描述<a href="https://medium.com/@jamielolo/react-component-%E5%85%83%E4%BB%B6-4c572fcd4979">元件</a>中可以使用的不同狀態，並且在它們之間轉換，以回應使用者輸入 ( input )，而不是直接操縱個別部分 UI。</p><h4>How declarative UI compares to imperative</h4><p>當在設計 UI 互動時，可能會去思考，該怎麼改變 UI 來回應使用者的動作。</p><p>以一個能讓使用者提交答案的表格為例：</p><ul><li>當在表格內輸入內容的時候，提交按鈕轉換為啟用 ( enabled )。</li><li>當點擊提交時，表格與按鈕轉換為禁用 ( disabled )。</li><li>當請求成功時，表格隱藏，出現 “謝謝” 的訊息。</li><li>當請求失敗時，顯示錯誤訊息，表格再度轉換為啟用 ( enabled )。</li></ul><p>在指令式編程 ( imperative programming ) 中，以上所述直接對應到你如何執行互動，你必須寫出明確的指令來操縱 UI。</p><p>開發者與電腦的關係，就像是乘客與司機，乘客下達指令，司機遵從指令：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*gG3YZ1yGzxg-BZOj26cnmA.png" /></figure><p>他們並不知道你想去哪，如果指引錯誤，將停止在錯誤的地方。<br>由於必須去命令每個元素，告訴電腦該如何更新 UI，因此稱為指令式 ( imperative )。</p><p>下方為一個指令式編程的範例，表格並非使用 React 編寫，而是使用瀏覽器內建的 DOM：</p><p>( 將左側拉桿向右移動，可以看見程式碼的部分，拉開後點擊左上角三條線漢堡圖示可以看見完整檔案，右邊則為輸出結果。 )</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Ffunny-cray-kpgmzv%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Ffunny-cray-kpgmzv%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fkpgmzv%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8099679284ba0053ece7a305f9d25ea/href">https://medium.com/media/f8099679284ba0053ece7a305f9d25ea/href</a></iframe><p>在一些規模較小的範例裡，指令式操作 UI 可以運作的很好。<br>但當系統變得複雜，就會變得難以管理。<br>以一張有不同內容的表格為例，新增一個 UI 元素或是互動，必須要非常的小心，確認每個動作不會導致 bug 發生 ( 像是忘了要顯示或隱藏 )。</p><p>React 解決了這個問題！</p><p>在 React 中，你不需要直接操縱 UI。<br>意思是：你不會直接啟用、禁用、顯示或隱藏元件。<br>你只需要宣告想顯示什麼，React 會幫我們解決更新 UI 的部分。</p><p>這就像是搭計程車的時候，我們告訴司機我們想去的地方，而不是命令他每個路口怎麼轉彎，讓乘客抵達目的地是司機的工作，而他們甚至會知道一些你沒有考慮過的捷徑。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*YPtyBAXpRNPOliqlTp-ESw.png" /></figure><blockquote>補充：這其實跟 React 採用 Virtual DOM 有關係，<br>關於 Virtual DOM 的介紹可以參照這篇 <a href="https://ithelp.ithome.com.tw/m/articles/10293802">Zet - DOM 與 Virtual DOM</a>。</blockquote><h4>Thinking about UI declaratively</h4><p>相同的範例，在 React 內是這麼執行的：</p><ol><li>辨別 ( Identify ) 元件不同的視覺狀態。</li><li>決定 ( Determine ) 觸發狀態改變的條件。</li><li>使用useState在記憶體中表示 ( Represent ) 它們的狀態。</li><li>移除 ( Remove ) 不必要的狀態變數。</li><li>連結 ( Connect ) 事件處理器以設置狀態。</li></ol><h4>Step 1: Identify your component’s different visual states</h4><p>電腦科學上的<a href="https://zh.wikipedia.org/zh-tw/%E6%9C%89%E9%99%90%E7%8A%B6%E6%80%81%E6%9C%BA">有限狀態機 ( state machine )</a>，是表示有限個狀態以及在這些狀態之間的轉移和動作等行為的數學計算模型。</p><p>與設計師一起工作時，你可能會看到不同視覺狀態的模型 。</p><p>這兩件事都是 React 的靈感來源。</p><p>首先，必須視覺化所有使用者可能會看見的 UI 狀態：</p><ul><li>Empty：表格提交按鈕為禁用。</li><li>Typing：表格提交按鈕為啟用。</li><li>Submitting：表格禁用。</li><li>Success：表格消失，出現 “謝謝” 的訊息。</li><li>Error：與 Typing 相同，只是會有錯誤訊息提示。</li></ul><p>在加入邏輯之前，為不同的狀態模組化或建立模型。</p><p>舉例來說，下方表格建立了視覺模型，而這個模型被 <a href="https://medium.com/@jamielolo/react-%E5%85%83%E4%BB%B6%E8%88%87-props-3b1200cec14d">props</a> 控制<br> (status = &#39;empty&#39;)：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Felegant-matan-jl4mbm%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Felegant-matan-jl4mbm%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fjl4mbm%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/863a39333e7cc3eef7706954847c50d2/href">https://medium.com/media/863a39333e7cc3eef7706954847c50d2/href</a></iframe><p>prop 可以任意命名。<br>請試著將status = &#39;empty&#39;改為status = &#39;success&#39;，並觀察輸出畫面的改變。</p><p>下方範例為同一個元件的應用，元件依舊受到statusprop 控制，可以試著改變每個status來觀察畫面顯示狀況：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Felastic-margulis-odbytp%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Felastic-margulis-odbytp%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fodbytp%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/1cb85ee8425640b19958a1783b2eb961/href">https://medium.com/media/1cb85ee8425640b19958a1783b2eb961/href</a></iframe><h4>【 DEEP DIVE 】</h4><p>即便一個元件有多個視覺狀態，也能輕鬆的將它們顯示在同一個頁面上，這樣頁面通常被稱為 “living styleguides” 或是 “storybooks”：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fserverless-browser-wg42kj%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fserverless-browser-wg42kj%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fwg42kj%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/098380da0f6b4f952a2e229fa60d82a1/href">https://medium.com/media/098380da0f6b4f952a2e229fa60d82a1/href</a></iframe><h4>Step 2: Determine what triggers those state changes</h4><p>我們可以觸發狀態更新來回應兩種類型的輸入：</p><ul><li>人為輸入：像是點擊按鈕、打字、導向連結。</li><li>電腦輸入：像是網路回應的抵達、計時完成、圖片加載。</li></ul><p>在這兩種情形下，我們必須設置狀態變數來更新 UI。<br>在我們開發的表格中，會需要改變狀態來回應不同的輸入：</p><ul><li>人為改變的輸入，需要將狀態從 Empty 改為 Typing，或是從 Typing 改回 Empty，這取決於文字輸入的狀況。</li><li>人為點擊提交按鈕，需將狀態轉換為 Submitting。</li><li>成功的網路回應，需將狀態轉換為 Success。</li><li>失敗的網路回應，需將狀態轉換為 Error，並給予相符的錯誤提示訊息。</li></ul><blockquote><strong>注意</strong>：人為輸入通常需要使用<a href="https://medium.com/@jamielolo/react-%E4%BA%8B%E4%BB%B6%E7%9B%A3%E8%81%BD%E5%99%A8-responding-to-events-fa661a652f8">事件處理器 ( event handlers )</a>。</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*ig_lY9BHZgSwbzk-jcQaPg.png" /></figure><h4>Step 3: Represent the state in memory with useState</h4><p>接下來，使用useState展現這些視覺狀態。<br>設計的關鍵在於越簡單越好，越複雜的設計將會導致更多的 bug。</p><p>首先，設計對應的狀態。<br>舉例來說，我們會需要設置正確答案與儲存發生錯誤的情況：</p><pre>const [answer, setAnswer] = useState(&#39;&#39;);<br>const [error, setError] = useState(null);</pre><p>接著，設置狀態變數來對應各種畫面顯示。<br>如果不知道該怎麼設置才好，可以先將所有可能的狀態寫出來。<br>或許這不是最好的辦法，但是重構狀態建立經驗也是過程之一：</p><pre>const [isEmpty, setIsEmpty] = useState(true);<br>const [isTyping, setIsTyping] = useState(false);<br>const [isSubmitting, setIsSubmitting] = useState(false);<br>const [isSuccess, setIsSuccess] = useState(false);<br>const [isError, setIsError] = useState(false);</pre><h4>Step 4: Remove any non-essential state variables</h4><p>為了避免重複的狀態內容，只能追蹤必要的狀態。<br>花一點時間在重構狀態結構上，將會使元件更容易理解、減少重複、避免產生預期外的結果。</p><p>目標：避免顯示出不想讓使用者看到的 UI。<br>舉例來說，你不會希望在發生錯誤時，同時禁用輸入框，這樣使用者將沒有機會修正內容。</p><p>以下幾種方法可以讓我們來檢視狀態變數：</p><ul><li>這個狀態會造成悖論嗎？<br>舉例來說，isTyping與isSubmitting不能同時為true。<br>悖論的發生，通常意味著狀態的定義不夠嚴謹。<br>依照 boolean 的邏輯去檢視，我們可以精簡為下面幾種狀態：<br>typing、submitting、success。<br>接著建立一個新的狀態status，將這三種狀態一起存進去。</li><li>同樣的資訊在其他狀態變數也可以獲得嗎？<br>另一種悖論：isEmpty與isTyping不能同時為true，將它們拆成兩種變數，會有產生 bug 的風險。<br>我們可以移除isEmpty，改為使用answer.length === 0來判別。</li><li>你可以在狀態變數的對立面找到同樣的資訊嗎？<br>isError是不需要存在的，透過error !== null來檢查即可。</li></ul><p>經過重構，我們成功將七種狀態變數精簡至三種：</p><pre>const [answer, setAnswer] = useState(&#39;&#39;);<br>const [error, setError] = useState(null);<br>const [status, setStatus] = useState(&#39;typing&#39;); // &#39;typing&#39;, &#39;submitting&#39;, or &#39;success&#39;</pre><h4>【 DEEP DIVE 】</h4><p>雖然這三種狀態已足夠展示我們的表格，但這中間有一些不合理的問題。</p><p>舉例來說，當status為success時，error不為 null 是一種不合理的情形，為了提升狀態的合理性，我們可以使用 redcer 來解決。<br>reducer 可以將狀態變數統一到一個物件裡，並且鞏固所有相關邏輯。</p><p>本篇只會大概提到 reducer 的功用，後面的篇章才會深入介紹。</p><h4>Step 5: Connect the event handlers to set state</h4><p>最後，建立事件處理器來設置狀態變數。</p><p>下方的範例為這個表格示範的最終版本。<br>在這個範例裡，我們成功串連了所有的顯示狀態：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fboring-galois-5cw764%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fboring-galois-5cw764%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F5cw764%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0d29ac8707b7dbecec5af5a01af3928/href">https://medium.com/media/d0d29ac8707b7dbecec5af5a01af3928/href</a></iframe><p>雖然程式碼比原本指令式的範例長，但此方法較為穩妥。<br>這也讓你可以在不去編寫邏輯的情況下，改變各種 UI 的展示狀態。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad06f9e7798c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【 React 】更新陣列類型的 state]]></title>
            <link>https://medium.com/@jamielolo/react-%E6%9B%B4%E6%96%B0%E9%99%A3%E5%88%97%E9%A1%9E%E5%9E%8B%E7%9A%84-state-948f6f18da00?source=rss-9dca7ca3c1ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/948f6f18da00</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-state]]></category>
            <dc:creator><![CDATA[Jamie Lo]]></dc:creator>
            <pubDate>Sat, 25 Feb 2023 07:20:31 GMT</pubDate>
            <atom:updated>2023-02-25T07:20:31.754Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sqq49x-335LMtJJa" /><figcaption>Photo by <a href="https://unsplash.com/@pawel_czerwinski?utm_source=medium&amp;utm_medium=referral">Pawel Czerwinski</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>本篇筆記摘錄自官方文件 <a href="https://beta.reactjs.org/learn/updating-arrays-in-state">Updating Arrays in State</a></blockquote><p>陣列在 JavaScript 中是可變的 ( mutable )，但當<a href="https://medium.com/@jamielolo/react-%E7%8B%80%E6%85%8B-state-30a8b791e4bc">狀態 ( state ) </a>類型為陣列時，應該要將它視為不可變的 ( immutable )。</p><p>mutable 意思為可變的、變異的，為避免名詞上的混淆，本篇會使用原文呈現。</p><p>與物件相同，當需要更新狀態裡的陣列時，需要先創建一個新的 ( 或是複製原本的那個 ) 陣列，並且使用新的陣列來設置狀態。</p><blockquote>物件類型的狀態更新與 mutate 相關可參考這篇：<a href="https://medium.com/@jamielolo/react-%E6%9B%B4%E6%96%B0%E7%89%A9%E4%BB%B6-state-9e3a051f4561">更新物件類型的 state</a></blockquote><h4>Updating arrays without mutation</h4><p>在 JavaScript 中，陣列的類型即是物件。<br>在 React 狀態裡，我們必須把陣列視為唯讀。<br>不能在陣列內重新指派，像是arr[0] = &#39;bird&#39;，也不能使用陣列方法 mutate 內容，像是push()與pop()。</p><p>需要更新陣列狀態時，需要建立一個新的陣列傳入狀態設置函式，可以使用一些 non-mutating 的方法來複製陣列，像是filter()與map()。</p><p>React 官方文件幫我們列出了一張表，裡面分類了陣列中的方法，左邊是應該避免使用的方法，右邊則是推薦使用的方法：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*USrslyPQd1I5R4Tvgcb71g.png" /></figure><p>如果使用 Immer，雙欄的方法都是可用的。</p><h4>【 Pitfall 】</h4><p>需注意slice與splice的差別：</p><ul><li>slice可以拷貝整個陣列，或是一部分的陣列。</li><li>splice會 mutate 陣列 ( 插入或刪除 )。</li></ul><h4>Adding to an array</h4><p>以下為使用push()方法的錯誤範例：</p><p>( 將左側拉桿向右移動，可以看見程式碼的部分，拉開後點擊左上角三條線漢堡圖示可以看見完整檔案，右邊則為輸出結果。 )</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fdank-frost-rqytth%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fdank-frost-rqytth%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Frqytth%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/d44b5c3303683a50acf1da3e62a6dc7a/href">https://medium.com/media/d44b5c3303683a50acf1da3e62a6dc7a/href</a></iframe><p>正確的方法是創建一個新的陣列，這個陣列會包含原有的內容，以及欲更新的內容，方法有非常多種，但使用展開運算子是最容易的一種：</p><pre>setArtists( // Replace the state<br>  [ // with a new array<br>    ...artists, // that contains all the old items<br>    { id: nextId++, name: name } // and one new item at the end<br>  ]<br>);</pre><p>以下為修正後的完整程式碼：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fawesome-mountain-ucguzz%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fawesome-mountain-ucguzz%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fucguzz%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/9369ecae4e8c5610dfbc187cbb447072/href">https://medium.com/media/9369ecae4e8c5610dfbc187cbb447072/href</a></iframe><p>也可以將展開運算符的順序移到後面，下面這段程式碼會先執行push()，把內容從陣列尾端推進去，再使用unshift從陣列前端推入資料：</p><pre>setArtists([<br>  { id: nextId++, name: name },<br>  ...artists // Put old items at the end<br>]);</pre><h4>Removing from an array</h4><p>最簡單的移除方法為filter，請試著點擊右側輸出畫面的 Delete 按鍵：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fbrave-murdock-g1jqts%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fbrave-murdock-g1jqts%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fg1jqts%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/37c4496cd5ae98059f4a6d5ad79df948/href">https://medium.com/media/37c4496cd5ae98059f4a6d5ad79df948/href</a></iframe><p>下面這段程式碼的意思是：<br>創建一個新的陣列，只有符合a.id !== artist.id條件的才能放入新陣列，filter並沒有更動到原陣列：</p><pre>setArtists(<br>  artists.filter(a =&gt; a.id !== artist.id)<br>);</pre><h4>Transforming an array</h4><p>如果想要改變陣列部分或全部的項目，可以使用map()來創建一個新的陣列，在map()內的函式寫出要對每個項目做哪些事情。</p><p>以下面這個例子來說，陣列包含了兩個圓形與一個方形的座標，每點擊一次上方按鍵，圓形就會向下 50 px，這是透過map()創建新陣列所達成的功能：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fnew-darkness-izexy3%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fnew-darkness-izexy3%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fizexy3%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec7ee48474cfff96cecadd03bb6a817d/href">https://medium.com/media/ec7ee48474cfff96cecadd03bb6a817d/href</a></iframe><h4>Replacing items in an array</h4><p>需要在陣列替換一個或多個項目的狀況是很常見的。<br>如一開始所說的：arr[0] = &#39;bird&#39;是 mutate 的行為。<br>在這邊我們也可以使用map()，map()方法中的第二個引數為索引值：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fboring-galois-opjfs5%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fboring-galois-opjfs5%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fopjfs5%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/7cf52874f5a20bcb5fa53cf74bf66097/href">https://medium.com/media/7cf52874f5a20bcb5fa53cf74bf66097/href</a></iframe><h4>Inserting into an array</h4><p>情況模擬：在特定的位置插入項目 ( 不是最前面也不是最後面的位置 )。<br>解法：使用展開運算子搭配slice()。</p><p><a href="https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/slice">MDN - Array.prototype.slice()</a></p><p>下方的這個範例，點擊 Insert 按鍵時，會將新項目插入索引值為 1 的位置：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fvibrant-james-s6q9f3%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fvibrant-james-s6q9f3%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fs6q9f3%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/de057f895380e2f3638a12acb19c1817/href">https://medium.com/media/de057f895380e2f3638a12acb19c1817/href</a></iframe><h4>Making other changes to an array</h4><p>【 綜合練習題 】<br>模擬情況：反轉陣列或是排序陣列。</p><p>JavaScript 中的reverse()與sort()方法會 mutate 原始陣列，因此不能直接使用這些方法。</p><p>我們需要先複製陣列，再進行改變：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fstill-feather-ym4s5u%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fstill-feather-ym4s5u%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fym4s5u%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c1ef335c80ae05238d2bb0cc9f22256/href">https://medium.com/media/9c1ef335c80ae05238d2bb0cc9f22256/href</a></iframe><p>在這個範例裡，首先使用了[...list]來複製陣列，接著直接對複製的陣列使用reverse()方法。</p><p>然而，即便複製了新的陣列，我們也不能使用 mutate 的方法直接改變已存在項目的內容，以下方這段程式碼為例，雖然nextList與list是不同的陣列，但是nextList[0]與list[0]指向了同一個物件，因為展開運算子是一種淺拷貝，改變nextList[0].seen將會同時改變list[0].seen：</p><pre>const nextList = [...list];<br>nextList[0].seen = true; // Problem: mutates list[0]<br>setList(nextList);</pre><h4>Updating objects inside arrays</h4><p>物件並非真的位於陣列的“裡面”，它們可能會在程式碼中出現在 “裡面”，但每個在陣列中的物件都是分開的值，它們有各自指向的 reference。</p><p>以下面這個範例來說，點擊其中一個人的列表，將會影響到另一個人：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fintelligent-snyder-46d808%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fintelligent-snyder-46d808%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F46d808%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/58bf8640282d297ac36727afa38e3d23/href">https://medium.com/media/58bf8640282d297ac36727afa38e3d23/href</a></iframe><p>問題是出在這段程式碼：</p><pre>const myNextList = [...myList];<br>const artwork = myNextList.find(a =&gt; a.id === artworkId);<br>artwork.seen = nextSeen; // Problem: mutates an existing item<br>setMyList(myNextList);</pre><p>雖然nextList本身是一個新的陣列，但內部的項目與myList是一樣的。<br>所以改變artwork.seen會改變原始的項目，而yourArtWorks內也有 artwork 的部分，這便是造成 bug 出現的原因。</p><p>或許這樣的 bug 不容易找到原因，但如果你沒有對狀態使用 mutate 的方式改變，就可以避免此類型的 bug 發生。</p><p>我們可以使用map()方法替換舊的項目：</p><pre>setMyList(myList.map(artwork =&gt; {<br>  if (artwork.id === artworkId) {<br>    // Create a *new* object with changes<br>    return { ...artwork, seen: nextSeen };<br>  } else {<br>    // No changes<br>    return artwork;<br>  }<br>});</pre><p>使用展開運算子複製陣列並進行替換，這樣便可以修復上述 bug：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Feager-lewin-8sk5hs%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Feager-lewin-8sk5hs%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F8sk5hs%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c82d5055b933c59c36f293beff13f82/href">https://medium.com/media/7c82d5055b933c59c36f293beff13f82/href</a></iframe><p>一般來說，你只能在物件剛創建時 mutate 它，如果想要處理已存在的狀態，則需要先複製一個新的物件。</p><h4>Write concise update logic with Immer</h4><p>跟上一篇一樣，官方文件在最後介紹了 <a href="https://github.com/immerjs/use-immer">Immer</a> 使用方法。</p><ul><li>如果狀態裡的物件結構非常多層，你可能會想要重構它們。</li><li>但如果你不想改變狀態的結構，你可以使用 Immer，Immer 讓我們可以使用 mutate 的寫法去更新物件，它會幫我們產出與複製新的陣列。</li></ul><p>下方的範例與前面的相同，只是改成 Immer 的寫法：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fcharming-minsky-gtpqiy%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fcharming-minsky-gtpqiy%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fgtpqiy%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/028286e2b774aba3412e025899c15251/href">https://medium.com/media/028286e2b774aba3412e025899c15251/href</a></iframe><p>在 Immer 裡，可以使用 mutate 的寫法：</p><pre>updateMyTodos(draft =&gt; {<br>  const artwork = draft.find(a =&gt; a.id === artworkId);<br>  artwork.seen = nextSeen;<br>});</pre><p>這是因為我們並沒有 mutate 原始狀態，而是 mutate 一個由 Immer 提供的特別物件draft，使用 Immer 時，也可以使用像是push()或pop()來改變內容。</p><p>Immer 會透過我們對draft所做的事情，建構出新的狀態內容，使用 Immer 可以讓程式碼變得更為簡潔。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=948f6f18da00" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>