<?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 Jian-Kai,Kuo on Medium]]></title>
        <description><![CDATA[Stories by Jian-Kai,Kuo on Medium]]></description>
        <link>https://medium.com/@JainKai?source=rss-ceec4ab9674f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*oh-6zCStOA6tqYsn</url>
            <title>Stories by Jian-Kai,Kuo on Medium</title>
            <link>https://medium.com/@JainKai?source=rss-ceec4ab9674f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 00:29:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@JainKai/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[[淺談]用GitHub Actions 簡易的 CI 來發布GitPages]]></title>
            <link>https://medium.com/@JainKai/%E6%B7%BA%E8%AB%87-%E7%94%A8github-actions-%E7%B0%A1%E6%98%93%E7%9A%84-ci-%E4%BE%86%E7%99%BC%E5%B8%83gitpages-6ae48e52467e?source=rss-ceec4ab9674f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ae48e52467e</guid>
            <category><![CDATA[github-pages]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Jian-Kai,Kuo]]></dc:creator>
            <pubDate>Wed, 02 Sep 2020 14:04:48 GMT</pubDate>
            <atom:updated>2020-09-02T14:04:48.755Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jIfuqGX6qvGikHhVrQ5eTg.jpeg" /><figcaption>圖片來源：<a href="https://i.ytimg.com/vi/E1OunoCyuhY/maxresdefault.jpg">https://i.ytimg.com/vi/E1OunoCyuhY/maxresdefault.jpg</a></figcaption></figure><p>大家好，今天要跟大家介紹要如何用 GitHub Actions 在指定分支上有 commit 時，就會更新 GitHub Page(展示用靜態頁面)。</p><p>首先，我們可以在想要的專案中，建立一個分支叫做 gh-pages 。接下來，我們將專案中要展示的 html、js、css 等等檔案，在 gh-pages 上 commit 和 push 。我們就可以透過 <strong>username.github.io/repository_name </strong>，上述這個網址結構來瀏覽我們的靜態頁面了。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*YHGckR8XawnpSszsD7rM4Q.png" /><figcaption>分支名稱為 gh-pages</figcaption></figure><p>大約在 2019年的時候，GitHub 推出了 Actions 可以讓我們設定一系列的 CI/CD 設定。所以，我們可以透過 GitHub Actions，當指定的分支有 commit 的時候，自動地幫我們部署一個版本上去 gh-pages 的分支上。</p><p>接下來是 GitHub Actions 簡單的設定方法。</p><h3>Personal Access token</h3><p>首先我們必須先到 <strong><em>Setting</em></strong> 產生一組可以訪問 repo 的 token。<a href="https://github.com/settings/tokens">https://github.com/settings/tokens</a> (token 產生的頁面)<br>勾選 repo，然後產生一組 token ，記得先把 token 複製在本機上或是用相機拍下，一但離開頁面就再也看不到 token 內容。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NOzfIE4BCw8u2a1mD5PnVw.png" /><figcaption>點擊 Generate new toke</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ht377OC373XCyCginkIYgw.png" /><figcaption>勾選 repo</figcaption></figure><h3>Secrets</h3><p>我們取得 <strong><em>access token</em></strong> 後，接者到我們要設定的 <strong><em>repo</em></strong> 中的 <strong><em>Settings </em></strong>選擇 <strong><em>Secrets</em></strong>，點擊<strong><em> new secret </em></strong>加入我們剛剛得到的<strong><em> access token 。</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RokZBYaNW1FSSNOPo6fkbw.png" /><figcaption>填入 Name 跟 Value，Value 就是 access token</figcaption></figure><p>設定完 <strong><em>Secrets </em></strong>後，可以設定 <strong><em>workflow</em></strong> 腳本了。</p><h3>Workflow</h3><p>GitHub Actions 是透過設定一系列的腳本來運行 CI/CD 的流程，因此我們需要將腳本的內容寫在一個 <strong><em>workflow.yml</em></strong> 的檔案中。</p><p>產生 <strong><em>workflow.yml </em></strong>有兩個方式。<br>一個是直接在 repo 中建立 <strong><em>.github/workflows/workflow.yml。<br></em></strong>另一個方法是在 Actions 分頁裡產生樣板，GitHub 裡已經有許多環境的樣板。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dCN35zOs2NeGqRxnFmNVkQ.png" /><figcaption>Actions 點擊 New workflow</figcaption></figure><p>這裡我是用第二種方式然後選擇 <strong><em>NodeJS</em></strong> 的樣板。</p><p>下面是我的設定檔，部署的專案用 <strong><em>NextJS 。<br></em></strong>其中 <strong><em>${{secrets.COMMIT_SECRET}} </em></strong>就是我們剛剛設定的<strong><em> Secrets。</em></strong></p><pre>name: Node.js CI<br><br>on:<br>  push:<br>    branches: [master]<br><br>jobs:<br>  build:<br>    name: Build and deploy gh-pages<br>    env:<br>      commit_secret: ${{secrets.COMMIT_SECRET}}<br>      USER_NAME   : [username]<br>      USER_EMAIL  : [useremail]<br>    runs-on: ubuntu-latest<br>    <br>    steps:<br>      - name: Checkout<br>        uses: actions/checkout@v1<br><br>      - uses: actions/setup-node@v1<br>        with:<br>          node-version: &#39;10.15.1&#39;<br>          registry-url: &#39;https://registry.npmjs.org&#39;<br><br>      - name: Install Yarn<br>        run: npm install -g yarn<br><br>      - name: Yarn Install<br>        run: yarn<br><br>      - name: deploy<br>        run: |<br>          rm -rf node_modules/.cache<br>          yarn build<br>          yarn export<br>          touch out/.nojekyll<br>          cd ./out<br>          git init<br>          git config --global user.email tony14256@gmail.com<br>          git config --global user.name tony14256<br>          git status<br>          git remote add origin https://${{secrets.COMMIT_SECRET}}@github.com/[username]/[repo-name].git<br>          git checkout -b gh-pages<br>          git add --all<br>          git commit -m &quot;Deploy Next.js to gh-pages&quot; <br>          git push origin gh-pages -f<br>          echo 🤘 deploy gh-pages complete.</pre><p>上述設定都設定完後，當我們在 master 分支上有任何 commit 時， GitHub Actions 就會依照 workflow.yml 設定的腳本內容，發佈一個版本到 gh-pages 分支上。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5oqTUkeJnIPPz7sEbeP-1g.png" /><figcaption>GitHub Actions 成功失敗的紀錄</figcaption></figure><p>以上是我利用 <strong><em>GitHub Actions</em></strong> 來部署 <strong><em>GitPages</em></strong>，透過自動化的過程就可以省去每次都要打指令部署的過程。</p><p>最後希望大家都可以在自己的專案中透過 <strong><em>GitHub Actions </em></strong>來進行自動部署。</p><p>參考資料：</p><p><strong><em>[1] </em></strong><a href="https://medium.com/ichef/use-github-actions-as-basic-ci-60e0136ebd8a"><strong><em>使用 Github Actions 作為簡易 CI</em></strong></a><strong><em><br>[2] </em></strong><a href="https://medium.com/@milkmidi/%E6%B7%B1%E5%85%A5%E4%BD%86%E4%B8%8D%E6%B7%BA%E5%87%BA-%E5%A6%82%E4%BD%95%E7%94%A8-github-actions-%E8%87%AA%E5%8B%95%E7%99%BC%E4%BD%88-gh-pages-8183464dfe84"><strong><em>深入但不淺出，如何用 github actions 自動發佈 gh-pages</em></strong></a><strong><em><br>[3] </em></strong><a href="https://github.com/features/actions"><strong><em>GitHub 官網介紹</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ae48e52467e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[淺談]在 Laravel 中使用 GraphQL(三)]]></title>
            <link>https://medium.com/lion-f2e/%E6%B7%BA%E8%AB%87-%E5%9C%A8-laravel-%E4%B8%AD%E4%BD%BF%E7%94%A8-graphql-%E4%B8%89-d8ce84f2f065?source=rss-ceec4ab9674f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8ce84f2f065</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel-5]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[graphql-playground]]></category>
            <dc:creator><![CDATA[Jian-Kai,Kuo]]></dc:creator>
            <pubDate>Tue, 26 Nov 2019 06:23:30 GMT</pubDate>
            <atom:updated>2019-11-26T06:23:30.037Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v_bFZcGA4g6sfHAXhRQuUw.png" /><figcaption>圖片來自： <a href="https://blog.pusher.com/graphql-laravel/">https://blog.pusher.com/graphql-laravel/</a></figcaption></figure><h3>前言</h3><p>上一次我們談到了兩件事情，一是透過 Laravel 的 factory 跟 seed ，根據資料表的屬性產生大量的資料，並且將其寫入資料庫中；二是我們在 Laravel 上使用 GraphQL ，建立了 Query 跟 Type 來完成 GraphQL 中基礎的 schemas ，之後也利用了 GraphQL playground 來向資料庫請求商品資料表中的資料。</p><p>這次我們會談到當資料表之間有關聯時，如何在 model 之間建立連結，接者透過 GraphQL 向資料庫請求完整的資料；接者，當我們需要新增或是修改資料時，如何透過 Mutation 來達到資料的修改或新增。</p><h3>Laravel：model relation→GraphQL： related Type</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*6Yo6T-nmTyA2vMsOrfCQeg.png" /><figcaption>資料表之間的關聯圖</figcaption></figure><ol><li>products.id → product_tag_ralated.product_id</li><li>product_tag_ralated.tag_id → product_tags.id</li><li>products.product_category_id → product_category.id</li></ol><p>上面的圖表與列表表達了我們在四張資料表之間的關聯，我們可以從 products 的 product_category_id 去對應到 product_categories 的 id，因此我們就可以知道 product 的商品類別是甚麼了；依此類推，來找到商品的標籤有哪些。</p><p>首先，我們需要先在 <strong><em>App\Product.php</em></strong> 新增與商品類別的關聯。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*o0Tt9MCNxKXs7CzR5Y7xgA.png" /><figcaption><strong><em>App\Product.php </em></strong><em>與 category的關聯</em></figcaption></figure><p>因為一個商品只會對應到一個商品類別，所以它們的關係是一對一的關係，所以透過 <a href="https://laravel.tw/docs/5.2/eloquent-relationships#one-to-one">Laravel 的 hasOne</a> 方法來建立關聯；其中第一個參數代表是的關聯資料表 model ，第二個可以設定為關聯對應的外鍵名稱，第三個則是關聯的外鍵名稱，關於參數的詳細說明可以到 <a href="https://laravel.tw/docs/5.2/eloquent-relationships#one-to-one">Laravel 的官方文件</a>去了解。</p><p>接者在 <strong><em>App\GraphQL\Type\ProductType.php</em></strong> 中加入 category 的屬性。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*mflW074OtQCASRtaOc8LPQ.png" /><figcaption><strong><em>App\GraphQL\Type\ProductType.php </em></strong><em>新增類別的屬性</em></figcaption></figure><p>之後我們就可以在 graphql-playground 上測試看看是否有成功 query 到類別的資料。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5EQ4TAr6J6tMnw7nfyWcUg.png" /><figcaption>graphql-playground 成功獲得 category 的資料</figcaption></figure><p>成功獲得商品類別的資料後，接者我們想要知道該商品的標籤有哪些？在 product_tag_related 這張資料表告訴了我們 product 與 product_tag 兩張資料表的對應關係，一個商品可能會有多個標籤，一個標籤也有可能會被多個商品擁有；在 <a href="https://laravel.tw/docs/5.2/eloquent-relationships#many-to-many">Larevel 官方文件</a>中提到這是一個多對多的關係。</p><p>因此，我們需要先在 <strong><em>App\Product.php</em></strong> 新增與商品標籤的關聯。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*i-_nWQYDg3vT_QJqnXtSbQ.png" /><figcaption><strong><em>App\Product.php </em></strong><em>與 tag 的關聯</em></figcaption></figure><p>belongsToMany 有四個參數，第一個參數一樣是關聯的 model ，第二個為兩者之間的關係資料表名稱， 第三個參數是關聯中的模型的外鍵名稱，而第四個則是要合併的模型中的外鍵名稱。詳細的說明可以去<a href="https://laravel.tw/docs/5.2/eloquent-relationships#many-to-many"> Laravel 的官方文件</a>了解。</p><p>接者在 <strong><em>App\GraphQL\Type\ProductType.php</em></strong> 中加入 tag 的屬性。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*RnAZMXXK6IOalNbxw0ltgw.png" /><figcaption><strong><em>App\GraphQL\Type\ProductType.php </em></strong><em>新增標籤的屬性</em></figcaption></figure><p>因為一個商品可能會有多個標籤，所以在前面用 listOf 的方式列舉出條件的資料。</p><p>之後我們一樣可以在 graphql-playground 上測試看看是否有成功 query 到標籤的相關資料。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jqci7qeIZUERhDhGVfDHlw.png" /><figcaption>graphql-playground 成功獲得 tag 的資料</figcaption></figure><p>到目前為止我們已經可以透過 GraphQl 向資料庫請求資料了，也成功將資料表之間的關聯建立起來了；接下來我們希望可以像資料庫新增或是修改一筆資料。</p><h3>GraphQL：Mutation</h3><p>在 a<strong><em>pp\GraphQL\Mutation </em></strong>新增一個 <strong><em>CreateProductMutation.php</em></strong> ，在裡面我們會設定在新增一筆商品時需要給予的參數，以及接收到參數後要如何進行處理。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7472a4079b10a757f2593e51bab4e0b3/href">https://medium.com/media/7472a4079b10a757f2593e51bab4e0b3/href</a></iframe><p>其中，在 tags 的參數是用字串的方式傳入，然後將字串切割後再與商品 ID 依序寫入 product_tag_related 資料表中。</p><p>之後到 app\Product.php 與 app\ProductTagRelated.php 中依序加入下面程式碼，為了要讓 model 知道那些屬性是能夠被寫入的。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*dbebeMbDdDVoMEEMDfH7Xw.png" /><figcaption>app\Product.php</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*JZX4kLZYACvdxHxK22eiwQ.png" /><figcaption>app\ProductTagRelated.php</figcaption></figure><p>最後，我們在 <strong><em>config\graphql.php </em></strong>中加入 Mutation 的相關設定就完成了所有步驟。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*EKB6TftNkI9aDmmCpTUZZw.png" /><figcaption><strong><em>config\graphql.php </em></strong><em>加入設定</em></figcaption></figure><p>我們一樣到 graphql-playground 來測試看看能不能新增資料到資料庫中。下面的結果圖可以知道 GraphQL 有成功新增一筆資料，而且 id 會自動遞增。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vWUk-NISji5YCJ163jPM1A.png" /><figcaption>GraphQL 成功新增一筆資料</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*FdCL4SmicmRqM9MI9QvA6g.png" /><figcaption>在資料庫中也看到第 51 筆資料被新增了</figcaption></figure><p>更新單筆資料可以參考下面的範例。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8facfca882525aea2e08a20f632373a1/href">https://medium.com/media/8facfca882525aea2e08a20f632373a1/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kwhbkh0SPnj6xt6xMGHaFw.png" /><figcaption>graphql-playground 的結果</figcaption></figure><h3>結論</h3><p>終於，我們談完了如何在 Laravel 上使用 GraphQL 來向資料庫請求資料，但這只是一個初步的開始，還必須要去思考要如何防止被攻擊以及使用者的身份驗證的問題…等等，這些都值得一在地討論以及研究，還有在 resolve 向資料庫請求或是修改資料時，如何才能夠達到高效率。</p><p>總之，不管是哪種 php 的 Laravel 也好， GraphQL 也好，都只是一款工具，在我們學會了這些工具後，該如何去發揮我們所學，從我們所學的去解決遇到的問題才是一門學問。</p><p>謝謝各位的觀看，如有任何問題或是有寫錯的部分也可以在下方留言。</p><h3>相關參考資料：</h3><p>graphql-laravel：</p><p><a href="https://github.com/rebing/graphql-laravel">rebing/graphql-laravel</a></p><p>Laravel 官方文件：</p><p><a href="https://laravel.tw/docs/5.3">安裝</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8ce84f2f065" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lion-f2e/%E6%B7%BA%E8%AB%87-%E5%9C%A8-laravel-%E4%B8%AD%E4%BD%BF%E7%94%A8-graphql-%E4%B8%89-d8ce84f2f065">[淺談]在 Laravel 中使用 GraphQL(三)</a> was originally published in <a href="https://medium.com/lion-f2e">LT Lab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[淺談]在 Laravel 中使用 GraphQL(二)]]></title>
            <link>https://medium.com/lion-f2e/%E6%B7%BA%E8%AB%87-%E5%9C%A8-laravel-%E4%B8%AD%E4%BD%BF%E7%94%A8-graphql-%E4%BA%8C-a315fd40c00b?source=rss-ceec4ab9674f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a315fd40c00b</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[graphql-playground]]></category>
            <category><![CDATA[xampp]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[laravel-5]]></category>
            <dc:creator><![CDATA[Jian-Kai,Kuo]]></dc:creator>
            <pubDate>Mon, 25 Nov 2019 05:49:06 GMT</pubDate>
            <atom:updated>2019-11-25T05:50:52.749Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V9QMa82Aq46W4PzcMp-spw.png" /><figcaption>圖片來自： <a href="https://blog.pusher.com/graphql-laravel/">https://blog.pusher.com/graphql-laravel/</a></figcaption></figure><h3>前言</h3><p>在上一篇淺談中，我們談到了透過 Xampp 架設 Laravel 框架，並且連接 MySQL 中的資料庫，最後透過指令將我們設定的 migraions 在資料庫中產生相對應的資料表。</p><h3>Laravel → factory + seeder → 資料庫新增資料</h3><p>Laravel 提供了可以自動產生資料的方法，透過在 factories 裡設定好要如何產生資料，就能夠在資料庫中自動的產出資料了。</p><p>我們打開 factories 中任意一個檔案會看到裡面空空如也，因為我們需要自己去撰寫資料表中每一筆資料是要如何去產生的。</p><pre>$factory-&gt;define([資料表model]::class, function (Faker $faker) {</pre><pre>    return [</pre><pre>        &quot;name&quot; =&gt; $faker-&gt;name, // Faker 中 隨機的 名稱</pre><pre>        &quot;product_type_id&quot; =&gt; mt_rand(1, 5), // 1~5隨機數字</pre><pre>        &quot;description&quot; =&gt; Str::random(4), // 隨機長度為4的字串</pre><pre>        &quot;price&quot; =&gt; mt_rand(10, 100),</pre><pre>    ];</pre><pre>});</pre><p>所以我們需要針對上次建立好的四個資料表的欄位進行各個欄位的資料填寫，由於資料需要一點隨機性，所以利用 <a href="https://github.com/fzaninotto/Faker">Faker </a>這個套件來隨機產生資料內容。</p><p>Faker 這個套件有許多已經寫好的資料內容可以去取用，詳細資料可以觀看 github 上的文件。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e4786a01ffb93cf4e7dc408909aa63b/href">https://medium.com/media/2e4786a01ffb93cf4e7dc408909aa63b/href</a></iframe><p>有了 factory 後我們需要有驅動工場的動力， seeder 就是可以驅動工廠的動能。首先，我們透過指令 php artisan make::seeder ProductSeeder ，會在 <strong><em>database/seeds</em></strong> 資料夾下新增 ProductSeeder.php 。</p><pre>$ php artisan make:seeder [Seeder Name]</pre><p>我們需要在 seeder 裡面設定每一個資料表需要產生的筆數或是要在資料庫中直接新增那些資料。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3959759b7d3b94a19142227baecb1a5/href">https://medium.com/media/a3959759b7d3b94a19142227baecb1a5/href</a></iframe><p>我們需要去 <strong><em>app</em></strong> 資料夾引用相關的 model，然後在 run 函式中設定要產生進去資料庫的資料筆數。</p><p>可以透過下面的指令產生資料：</p><pre>$ php artisan db:seed --class[seeder 的 class Name]</pre><p>執行完上面的指令後，到 MySQL 資料庫就可以看到四個資料表都填入設定好的資料筆數了。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*B9BBdW7iVVfxJWYrtysAcg.png" /><figcaption>資料表 products 中新增了 50 筆資料</figcaption></figure><p>我們在 <strong><em>database/seeds/DatabaseSeeder.php </em></strong>的 run function 中添加程式碼 $this-&gt;call(ProductSeeder::class); 指定到對應的 seeder ，就可以透過下面的指令，將現有的資料庫從新刷新，產生新的資料表跟資料。</p><pre>$ php artisan migrate:refresh --seed</pre><h3>GraphQL：安裝</h3><p>文章到了這邊終於進入了我們的主題「GraphQL」，到目前為止我們已經透過了 Laravel 成功地在資料庫中產生了幾筆資料，我們就可以透過 GraphQL 進行資料的撈取了。</p><p>首先，我們需要先安裝 GraphQL 的套件以及相關設定：</p><pre>$ composer require rebing/graphql-laravel</pre><p>接者到 <strong><em>config\app.php </em></strong>，在 providers 和 aliases 中加入：</p><pre>// providers<br>Rebing\GraphQL\GraphQLServiceProvider::class</pre><pre>//aliases<br>&#39;GraphQL&#39; =&gt; Rebing\GraphQL\Support\Facades\GraphQL::class</pre><p>接者執行 下面指令來產生 GraphQL 相關的 config 檔：</p><pre>$ php artisan vendor:publish --provider=&quot;Rebing\GraphQL\GraphQLServiceProvider&quot;</pre><p>最後會產生 <strong><em>config\graphql.php</em></strong> 並且看到相關的設定。</p><h3>GraphQL：Schemas</h3><blockquote>GraphQL相較於REST以及其他web service架構提供了一種高效、強大和靈活的開發web APIs的方式。它通過由客戶端根據所需定義資料結構，同時由服務端負責返回相同資料結構的對應數據的方式避免了服務端大量冗餘數據的返回，但與此同時也意味著這種方式不能有效利用起查詢結果的web緩存。GraphQL這種查詢語言所帶來的靈活性和豐富性的同時也增加了複雜性，使得這項技術對於簡單APIs並不是好的選擇。 <br>— 引用至 <a href="https://zh.wikipedia.org/wiki/GraphQL">https://zh.wikipedia.org/wiki/GraphQL</a></blockquote><p>GraphQl 是透過一串 query 指令像資料庫請求需要的相關資料，像是：</p><pre>query {<br>   users(id:5){<br>      id<br>      name<br>      job<br>   }<br>}</pre><p>上面的指令結構告訴了 GraphQL 我們要去 users 資料表中找到 id 為 5 的哪個 user 的 id 、 name 、 以及 job。</p><p>首先，我們先在 <strong><em>app </em></strong>資料夾中新增<strong><em> GraphQL </em></strong>資料夾，我們會將相關的檔案放置在這個資料夾中。</p><p>接者在 <strong><em>app\GraphQL</em></strong> 中新增三個資料夾，分別為 <strong><em>Mutation </em></strong>、 <strong><em>Query </em></strong>以及 <strong><em>Type </em></strong>，三個資料夾中放置的檔案有不同的功用。</p><ol><li><strong><em>Mutation</em></strong> 資料夾：負責資料的更新或是資料新增。</li><li><strong><em>Query </em></strong>資料夾：負責定義查詢時的參數以及處理。</li><li><strong><em>Type </em></strong>資料夾：負責 Query 時回傳的資料格式。</li></ol><p>資料夾建完資後，我們先到 <strong><em>app\Type</em></strong> 中新增 <strong><em>ProductType.php </em></strong>、<strong><em> ProductCategoryType.php </em></strong>以及<strong><em> ProductTagType.php</em></strong> 三個檔案。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/1*MTmzK5bwkNuoImWIILPtqA.png" /><figcaption>Type 資料夾</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb718249f2dbf04fb52a0a90812128de/href">https://medium.com/media/fb718249f2dbf04fb52a0a90812128de/href</a></iframe><p>定義完 Type 後，我們需要定義 Query 來讓 GraphQL 接收我們的 Query 字串。這次的淺談我們只針對商品進行資料的請求，因此我們只在 Query 資料夾中新增 ProductQuery.php ，來獲得商品的資料。若需要得到其他資料表的資料，可以參考 ProductQuery.php 是如何設置的。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6300787673372a1909baa3f0dcb8f2f7/href">https://medium.com/media/6300787673372a1909baa3f0dcb8f2f7/href</a></iframe><p>其中， <strong><em>type </em></strong>函式會從 <strong><em>config\graphql.php</em></strong> 的 type 中找到 product 的資料格式以及型別。<strong><em>resolve </em></strong>函式則是會簡單的判斷 query 的參數有 id 會去找出此 id 的商品，沒有則是回傳整個 products 資料表的商品資料。</p><p>接者要在 <strong><em>config\graphql.php </em></strong>設定 query 時的 schemas 跟 資料回傳時的 types。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*s9O8bjOEOkK1cTPlMkw6Bg.png" /><figcaption>在 <em>config\graphql.php 引用相關</em><strong><em> class</em></strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*snrwdCaWDsqZNYeDgV4M4Q.png" /><figcaption>在 schemas 中設定 product 的 query</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*2dxh6ENUpEWim3SCcuUSGA.png" /><figcaption>在 types中設定相關的 type</figcaption></figure><p>完成上述的動作後，我們就完成了基礎的 GraphQL 的設定了，接者我們需要在安裝測試工具來測試我們的 GraphQL 能不能作用了。</p><h3>GraphQL：安裝測試工具及測試</h3><p>這裡我們使用 <a href="https://github.com/mll-lab/laravel-graphql-playground">mll-lab/laravel-graphql-playground</a> 來測試我們設定好的 GraphQL 能不能作用。</p><pre>$ composer require mll-lab/laravel-graphql-playground</pre><p>在 <strong><em>config\app.php </em></strong>中加入 provider</p><pre>&#39;providers&#39; =&gt; [<br>    // Other providers...<br>    MLL\GraphQLPlayground\GraphQLPlaygroundServiceProvider::class,<br>]</pre><p>接者執行下面指令，產生 <strong><em>config/graphql-playground.php</em></strong> 。</p><pre>php artisan vendor:publish --provider=&quot;MLL\GraphQLPlayground\GraphQLPlaygroundServiceProvider&quot; --tag=config</pre><p>最後在瀏覽器打開 <a href="http://graphql.local/graphql-playground">http://graphql.local/graphql-playground</a> 就可以看到 GraphQL 的測試環境了。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U1Fw57Py0e5uqq5SANt8-w.png" /><figcaption>GraphQL 測試環境</figcaption></figure><p>測試看看可不可以從資料庫拿到資料。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dWegv7QSTw8D4NpRTFenCA.png" /><figcaption>成功拿到全部 product 資料</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8VX0pItCMFY0yvvHyvCvWA.png" /><figcaption>成功拿到 id 為 5 的 product 資料</figcaption></figure><p>這次的淺談，我們談到如何使用 factory 加上 seed 來產生資料集，接著透過 GraphQL 在資料庫裡面請求資料。而我們在這次也終於有提到了 GraphQL 的相關設定以及程式碼的演示，當我們將 Query 的 schema 結構定義清楚以及 resolve 該做出甚麼動作，我們就可以透過 GraphQL 來向資料庫請求資料了。</p><p>下一次的淺談，我們會談到如何處理資料表之間的關聯，以及如果要新增或式修改資料時該如何去處理。</p><p>謝謝各位的觀看，如有任何問題或是有寫錯的部分也可以在下方留言。</p><p>相關參考資料：</p><p>graphql-laravel：</p><p><a href="https://github.com/rebing/graphql-laravel">rebing/graphql-laravel</a></p><p>laravel-graphql-playground：</p><p><a href="https://github.com/mll-lab/laravel-graphql-playground">mll-lab/laravel-graphql-playground</a></p><p>在 Laravel 中使用 GraphQL 一【获取数据】：</p><p><a href="https://learnku.com/articles/8115/using-graphql-one-in-laravel-get-data">在 Laravel 中使用 GraphQL 一【获取数据】</a></p><p>多面體工作室 Dometi — Laravel</p><p><a href="https://dometi.com.tw/blog/category/%E7%B6%B2%E9%A0%81/%E7%B6%B2%E9%A0%81%E5%BE%8C%E7%AB%AF/laravel/">Laravel 彙整 - 多面體工作室 Dometi</a></p><p>Laravel 官方文件</p><p><a href="https://laravel.tw/docs/5.3">安裝</a></p><h3><strong>備註：</strong></h3><p>如果有遇到 Laravel 無法解析 class 的問題，可以參考下面連結的解決方法。</p><p><a href="https://stackoverflow.com/questions/32475892/reflectionexception-class-classname-does-not-exist-laravel#comment52814653_32475892">ReflectionException: Class ClassName does not exist - Laravel</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a315fd40c00b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lion-f2e/%E6%B7%BA%E8%AB%87-%E5%9C%A8-laravel-%E4%B8%AD%E4%BD%BF%E7%94%A8-graphql-%E4%BA%8C-a315fd40c00b">[淺談]在 Laravel 中使用 GraphQL(二)</a> was originally published in <a href="https://medium.com/lion-f2e">LT Lab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[淺談]在 Laravel 中使用 GraphQL(一)]]></title>
            <link>https://medium.com/lion-f2e/%E6%B7%BA%E8%AB%87-%E5%9C%A8-laravel-%E4%B8%AD%E4%BD%BF%E7%94%A8-graphql-%E4%B8%80-23bbe1b54d3a?source=rss-ceec4ab9674f------2</link>
            <guid isPermaLink="false">https://medium.com/p/23bbe1b54d3a</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[xampp]]></category>
            <category><![CDATA[laravel-framework]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Jian-Kai,Kuo]]></dc:creator>
            <pubDate>Fri, 22 Nov 2019 07:24:17 GMT</pubDate>
            <atom:updated>2019-11-22T07:24:17.931Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V9QMa82Aq46W4PzcMp-spw.png" /><figcaption>圖片來自： <a href="https://blog.pusher.com/graphql-laravel/">https://blog.pusher.com/graphql-laravel/</a></figcaption></figure><h3>前言</h3><p>有許多人會問，為什麼要使用 GraphQL ，而不是直接使用傳統的 RESTful API 就好了呢？簡單的在 Google 上谷歌 GraphQL 優勢或好處，自然就會看到許多文章，或許你也是從這裡看到這篇文章也不一定。</p><p>稍微簡介一下， GraphQL 與 RESTful API 不同的地方是， GraphQL 可以更直覺的對資料庫進行資料的要求，跟資料庫下 SQL 一樣，設定好 select 、 from 、 where 就能夠要求到需要的資料。在這個優勢下，以往一個頁面可能需要請求三到四支 API 才能夠得到足夠渲染的資料， GraphQL 可能只需要向後端伺服器請求一次就能夠獲取足夠的資料，能夠省去前後端溝通的時間及次數。</p><p>那為什麼會有這篇文章呢？簡單來說就是因為「潮」， Github 、 Shopify 、 Coursera 、 Twitter 等大型的公司都開始在用了，那我們也要來嘗試看看。</p><p>廢話不多說就開始淺談這次的教學。</p><h3>XAMPP + Laravel</h3><p>一開始我們需要先有能夠運行 php 的環境來執行 Laravel 的專案。</p><p>這裡我們採用的是 <a href="https://www.apachefriends.org/zh_tw/index.html">Xampp</a> ，Xampp 裡面包含了很多東西，其中有 MySQL 可以當作是存取的資料庫。若有自己已經有資料的資料庫，也可以使用自己熟悉的資料庫。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EvTcNUmUIPOXLHwr5oqyaw.png" /><figcaption>Xampp 的下載畫面，網址： <a href="https://www.apachefriends.org/zh_tw/index.html">https://www.apachefriends.org/zh_tw/index.html</a></figcaption></figure><p>下載完後，開啟 XAMPP Control ，把 Appche 與 MySQL 起動。啟動之後就可以打開瀏覽器前往 <a href="http://localhost/dashboard/">http://localhost/dashboard/</a>，會看到 Xampp 的介紹頁。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*9QeDW3TNKZJuM3uvqkz1iA.png" /><figcaption>Xampp 啟動 Apache 與 MySQL</figcaption></figure><p>接下來我們要去安裝 <a href="https://laravel.com/">Laravel </a>，是一個 PHP 的框架。在這之前需要先去安裝 <a href="https://getcomposer.org/">Composer</a> ，我們需要透過 Composer 來管理套件的相依性。</p><p>首先，使用 Composer 下載 Laravel installer：</p><pre>composer global require &quot;laravel/installer&quot;</pre><p>然後在指定的目錄下新增 Laravel 專案：</p><pre>laravel new GraphQL</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g1ZZQni14nEO67_zAXht0Q.png" /><figcaption>新增 Laravel 專案</figcaption></figure><p>這裡我們是透過 Apache 來執行我們的專案，所以需要做一些設定。先到 <strong><em>xampp/apache/conf/httpd.conf</em></strong> 以及 <strong><em>xampp/apache/conf/extra/httpd-vhosts.conf </em></strong>設定 Apache 的虛擬站台，這樣可以在瀏覽器看到我們專案的成果。</p><ul><li>在 <strong><em>xampp/apache/conf/httpd.conf </em></strong>確保 Include conf/extra/httpd-vhosts.conf 沒有備註解掉。</li><li>在 <strong><em>xampp/apache/conf/extra/httpd-vhosts.conf </em></strong>我們要去新增我們的虛擬站台。在 http-vhosts.conf 中加入：</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/850f29089b07d809c136e2907ae6be06/href">https://medium.com/media/850f29089b07d809c136e2907ae6be06/href</a></iframe><p>之後，我們去 C:\Windows\System32\drivers\etc\hosts 設定 hosts ，需要在最下面加上 127.0.0.1 GraphQL.local ，需要有系統管理員才能修改檔案。</p><p>全部設定完後打開瀏覽器到 <a href="http://graphql.local/">http://graphql.local/</a> 就能夠看到大大的 Laravel了，也就完成了基礎的設定了。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U257fIV8m7Sv0M_hPczwDA.png" /><figcaption>設定完後，看到Laravel 初始頁面</figcaption></figure><h3>Laravel → migratons → 資料庫新增資料表</h3><p>GraphQL 是要從資料庫中去獲取資料，因此我們需要先有一個資料庫，而且資料庫裏面需要有一小筆的資料。</p><p>首先我們在 Xampp 的控制面板上，點擊 MySQL 上 Admin 按鈕，打開 phpMyAdmin ，新增一個新的資料庫叫做 GraphDB ，我們會將資料寫入這個資料庫。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xOoQ5MpSF3VFqHood43ABQ.png" /><figcaption>MySQL 在 php 上的控制板</figcaption></figure><p>我們在資料庫中會新增 products 、 product_tags 、 product_category 、 product_tag_related 這四張資料表，來表達商品的種類、標籤等等關係。</p><p>首先要先到 .env 檔案中，設定要連接的資料庫、使用者名稱以及密碼。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*ya_rUnkqc-yXWAjHB8XCUA.png" /></figure><p>接者我們需要建立 model 與資料庫中的資料表互動，因此我們需要執行下列命令：</p><pre>$ php artisan make:model Product -fmr<br>$ php artisan make:model ProductTag -fmr<br>$ php artisan make:model ProductCategory -fmr<br>$ php artisan make:model ProductTagRelated -fmr</pre><p>上述每個指令後面的 -fmr 可以讓我們在產生 model 時，同一時間產生相對應的 migration 、 factory 。 migration 可以自動地在資料庫中產生資料表，而 factory 則是可以在資料表中自動地產生資料。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*yf_c0RKh2jG-kAoB417gLQ.png" /><figcaption>利用指令產生的 model 、 migration 以及 factory</figcaption></figure><p>接者打開每一個 migration ，我們要開始寫 code 了。Laravel 會根據 migration 在資料庫中建立對應的資料表。</p><p>在 migration 中會的 class 中會有 up 跟 down 兩個函式，分別代表建立資料表以及丟棄資料表。</p><pre>// 建立資料表<br>up(){ <br>    <em>Schema</em>::create([你的資料表名稱], function(Blueprint $table){<br>        $table-&gt;bigIncrements(&#39;id&#39;);  // 設定表格的欄位名稱以及欄位型別<br>    })<br>}</pre><pre>// 丟棄資料表<br>down(){ <br>    <em>Schema</em>::dropIfExists([你的資料表名稱])<br>}</pre><blockquote>欄位型別可以參考 Laravel 的<a href="https://laravel.com/docs/5.5/migrations">官方文件</a>。</blockquote><ol><li>product 的 migration 會建立 product 資料表的各個欄位以及型別。依此類推 product_tag 、 product_type 、 product_tag_related。</li><li>建立 product_tag_related 的目的是要能夠在資料庫中可以連接 product 以及 product_tag ，是屬於關聯式資料庫中 ER-model 中的 R 。</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b6f441497fb0d0855747463fe6a4f85/href">https://medium.com/media/1b6f441497fb0d0855747463fe6a4f85/href</a></iframe><p>接者就可以透過指令來在資料庫中建立資料表。</p><p>執行所有未完成的migrations</p><pre>php artisan migrate</pre><p>還原最後的migration動作</p><pre>php artisan migrate:rollback</pre><p>還原指定次數的migration動作</p><pre>php artisan migrate:rollback --step=5</pre><p>還原所有的migrations</p><pre>php artisan migrate:reset</pre><p>回到 phpMyAdmin ，進入 graphql 資料庫，我們可以看到透過指令建立的四個資料表。其中會看到 migrations 資料表，是用來記錄到目前為止各個資料表修改的次數，可以用來回朔資料表的狀態。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*t8jXEjlRmz3EC1nzLGRNew.png" /><figcaption>透過指令產生的四個資料表</figcaption></figure><p>這次的淺談，我們談到如何透過 Laravel 在 MySQL 上建立以及新增資料表。透過上述的方式，雖然前置動作有點多，但是我們可以自動化的產生資料表，也能夠回朔；當測試階段到了一定程度就可以把測試的假資料丟棄，或是開發階段發生錯誤，也可以把資料庫回到正確的時候。</p><p>下一次的淺談，我們會談如何透過 factory 跟 seeder 來自動的產生假資料，以及如何用 GraphQL 取得資料庫中的資料。</p><p>謝謝各位的觀看，如有任何問題或是有寫錯的部分也可以在下方留言。</p><p>相關參考資料：</p><p>[分享] Laravel</p><p><a href="https://medium.com/@app030242/2fb4431b8eb8">[分享] Laravel</a></p><p>多面體工作室 Dometi — Laravel</p><p><a href="https://dometi.com.tw/blog/category/%e7%b6%b2%e9%a0%81/%e7%b6%b2%e9%a0%81%e5%be%8c%e7%ab%af/laravel/">Laravel 彙整 - 多面體工作室 Dometi</a></p><p>Laravel 官方文件</p><p><a href="https://laravel.tw/docs/5.3">安裝</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23bbe1b54d3a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lion-f2e/%E6%B7%BA%E8%AB%87-%E5%9C%A8-laravel-%E4%B8%AD%E4%BD%BF%E7%94%A8-graphql-%E4%B8%80-23bbe1b54d3a">[淺談]在 Laravel 中使用 GraphQL(一)</a> was originally published in <a href="https://medium.com/lion-f2e">LT Lab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[實作]使用 Redux 實作 Todo-List]]></title>
            <link>https://medium.com/lion-f2e/%E5%AF%A6%E4%BD%9C-%E4%BD%BF%E7%94%A8-redux-%E5%AF%A6%E4%BD%9C-todo-list-43fd1d73d4c1?source=rss-ceec4ab9674f------2</link>
            <guid isPermaLink="false">https://medium.com/p/43fd1d73d4c1</guid>
            <dc:creator><![CDATA[Jian-Kai,Kuo]]></dc:creator>
            <pubDate>Sat, 10 Aug 2019 08:48:26 GMT</pubDate>
            <atom:updated>2019-08-10T08:48:26.231Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4L-GqAxAp7KsObMj.png" /><figcaption>圖片來源：<a href="https://redux.js.org/">https://redux.js.org/</a></figcaption></figure><h3>Redux 基礎概念</h3><p>Redux 的首頁就提到：<strong><em>Redux is a predictable state container for JavaScript apps</em></strong>，這句話指出Redux希望能夠提供一個容器，這個容器可以用來管理以及預測 State，讓開發這能夠在開發複雜的 Javascript app 下，對於資料狀態的控制能夠更加的簡便以及直覺。</p><p>P.S.：Redux的名字看起來好像與React有相關性，但是兩這之間並沒有相依性，Redux可以用在任何JavaScript框架，或是不用任何JavaScript框架。</p><h3>Redux 資料流</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oz32q7pI2vvWFXc8NM4Egg.png" /><figcaption>Redux 運作流程</figcaption></figure><ul><li><strong>ACTION：</strong>使用者透過觸發 ACTION ，來改變 STORE 中 STATE的狀態，一個 ACTION 通常包含 TYPE 和 PAYLOAD。</li><li><strong>REDUCER：</strong>REDUCER 會根據 ACTION 的 TYPE 去執行對應到的行為來改變 STORE 中 STATE 的狀態。</li><li><strong>STORE：</strong>將整個 JavaScript APP 的 STATE 集中起來進行管理以及儲存的容器，會將不同 STATE 用Object Tree的方式儲存起來。</li><li><strong>VIEW：</strong>當 STORE 中的 STATE 有改變的時候，會更新對應到的畫面(VIEW)。</li></ul><p>當使用者跟 VIEW 有互動的時候，會觸發了事件而發送 ACTION 到 REDUCER，REDUCER 會根據 ACTION 中的 TYPE 去對應到相對的行為然後回傳新的 STATE 到 STORE，而 VIEW 發現 STORE 中的 STATE 有改變的時候，就會從新繪製畫面。</p><h3>實作 Todo List</h3><p>首先，先用我們擅長用的 create-react-app 幫我們建立一個 React 專案，此時並沒有包含 Redux ，所以我們需要另外安裝它：</p><pre>npm install --save react-redux</pre><p>安裝完 react-redux 之後我們在 src 的資料夾下面，新增下列的資料夾，事實上我們不見得需要新增這些資料夾，多了這些資料夾會讓我們在 coding 的時候，容易管理程式碼的位置，以及維護的方便性。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*h-QEw1bZTffs30Cw4ynaHA.png" /><figcaption>資料夾架構</figcaption></figure><ul><li>actions → 在 actions 資料夾中會放入，當使用者觸發了畫面事件時，會執行哪些行為，像是輸入文字。</li><li>components → 設計好各個不同的 components。</li><li>constants → 可以存放一些常數，常見會在裡面放進不同 action 的行為常數；例如：『新增代辦事件』此行為就會以 ADD_TODO 來當作是這個行為的常數。</li><li>reducers → 當有使用者行為觸發了事件之後，我們需要根據事件的 type 來去執行相對應的動作，接者改變 store 內的 state。</li><li>store → 會將所有我們需要用到的 reducer 進行連結，打包成一個儲存 state 跟 action 的地方。</li></ul><p>首先，我們先分析一個基本的 TodoList ，使用者在使用得時候會觸發哪些行為 。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*TeTfomg4osMtKoKjcZp1Hg.png" /><figcaption>TodoList 畫面</figcaption></figure><p>分別有新增Todo 、完成Todo 、刪除Todo 以及輸入Todo Title ，我們根據這四個行為，在 action-type.tsx 中加入四個相對應的常數。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb33a73f735ef3c90554cdac51250918/href">https://medium.com/media/bb33a73f735ef3c90554cdac51250918/href</a></iframe><p>接者，我們可以開始設計 Store 中的 State 了。首先，我們到 Reducers 中新增 todoReducer.tsx 。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43eeddce1e1d80913e35015939879090/href">https://medium.com/media/43eeddce1e1d80913e35015939879090/href</a></iframe><p>todoReducer.tsx 分為兩個部分：</p><ul><li>initialState：為初始的 State 狀態，基本上跟在 component 裡設計 State 是一樣的像法；這個例子中，State 中有 todos 以及input ， todos 是一個陣列，存放所有代辦事項， input 是當輸入欄有更動時會改變 title 的文字。</li><li>todoReducer：當中包含兩個參數需要輸入， state 以及 action ， state 是這個 reducer 的 State， action 包含了這個行為的 type 以及 payload ； reducer 會根據 action.type 去執行相對應的行為，並且會根據 action.payload 來改變 state 的內容，而當 state 改變時，畫面就會從新渲染了。</li></ul><p>我們設計完 todoReducer 後，就要把 reducer 連接到 store 中，在 redux 中一個JavaScript App 只能有一個store ，但是我們在設計 APP 的時候，可能會有很多不同的 State，如果將這些 State 都寫在一個 reducer 中，會導致 reducer 中的程式碼很混亂，為了避免這個情況，我們可以根據 state 的功能來進行分類，之後在全部綁定成一個 rootReducer 中，儲存在store 中就可以了。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/918e12a880af4b67149da116b7dc5796/href">https://medium.com/media/918e12a880af4b67149da116b7dc5796/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/934bd87c2761c5598b6c3db2fc5826a3/href">https://medium.com/media/934bd87c2761c5598b6c3db2fc5826a3/href</a></iframe><p>我們可以將所有設計出來的 reducers ，透過 redux 的 combineReducers 集中綁定到 rootReducer 中後，在用 createStore 將 rootReducer 儲存到唯一的 store 中。</p><p>到這邊，大家可能會有疑惑說， reducer 的 action 參數是從哪裡來的。當我們在畫面上有行為產生，同時觸發了 action ，就是上述說的參數。</p><p>所以我們在剩下的資料夾 actions 新增 todoAction.tsx ， todoAction.tsx 裡面會描述有有關於相對的 reducer 的行為，回傳一個包含 action.type 以及 action.payload 的結構。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58fa2d2f841a7b369df43f964ce6af21/href">https://medium.com/media/58fa2d2f841a7b369df43f964ce6af21/href</a></iframe><p>上面程式碼可以看到我們針對了兩個行為， ADD_TODO 以及FINISH_TODO 做了兩個 action，最後分別回傳了一個物件，包含 type 以及payload(載體) ， type 就是 action 的常數， payload 則是要運送到 reducer 中要去做計算的負載物。</p><p>做完上述的動作後，我們就搞定我們的 action 、 reducer 以及 store 了，剩下就是讓我們的 TodoList 可以使用這些東西。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4e1834e9e59b1555fdbf8be79f4af9b/href">https://medium.com/media/a4e1834e9e59b1555fdbf8be79f4af9b/href</a></iframe><p>我們在 App.tsx 引入 store ，用 redux 的 Provider 將 store 載入我們的 TodoList 中。之後，我們就只要在需要用到 store的 component ，去連接需要的 state 以及 action 即可。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7481bed06f1d89bbb2ad8875eb029dc4/href">https://medium.com/media/7481bed06f1d89bbb2ad8875eb029dc4/href</a></iframe><ul><li>mapStateToProps 將 store 中提出需要用到的 state 。</li><li>mapDispatchToProps 會把 action 綁定在元件相對應的事件上 ，例如： onInput 會在輸入欄有變化的時候觸發，接者就會執行 changeInput ，接者回傳 action 物件給 reducer 進行處理。</li></ul><p>最後，將 mapStateToProps 以及 mapDispatchToProps 用 redux 提供的API connect 在元件上。</p><h3>總結</h3><p>到這個步驟，就完成了最基本的 Redux 設定了，接著就是熟能生巧，多用就能夠多熟悉 Redux 了。對於Redux 中處理非同步問題有興趣的話，可以去 <a href="https://redux.js.org/advanced/middleware">Redux官網</a>提到的 middlewave 去看看非同步問題是怎麼運作的。</p><p>最後，各位如果對文章內容有任何建議或指正，歡迎留言指教。</p><p>上述 TodoList 所使用的程式碼範例：<a href="https://github.com/tony14256/React-Redux-TodoList">https://github.com/tony14256/React-Redux-TodoList</a></p><h3>參考資料：</h3><ul><li><a href="https://rhadow.github.io/2015/07/30/beginner-redux/">Redux 入門</a></li><li><a href="https://github.com/kdchang/reactjs101/blob/master/Ch07/react-redux-introduction.md">kdchang/reactjs101</a></li><li><a href="https://redux.js.org/">Redux - A JS library for predictable and maintainable global state management | Redux</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43fd1d73d4c1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lion-f2e/%E5%AF%A6%E4%BD%9C-%E4%BD%BF%E7%94%A8-redux-%E5%AF%A6%E4%BD%9C-todo-list-43fd1d73d4c1">[實作]使用 Redux 實作 Todo-List</a> was originally published in <a href="https://medium.com/lion-f2e">LT Lab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[淺談High Order Component(HOC)]]></title>
            <link>https://medium.com/lion-f2e/%E6%B7%BA%E8%AB%87high-order-component-hoc-15c457352fc4?source=rss-ceec4ab9674f------2</link>
            <guid isPermaLink="false">https://medium.com/p/15c457352fc4</guid>
            <dc:creator><![CDATA[Jian-Kai,Kuo]]></dc:creator>
            <pubDate>Sat, 03 Aug 2019 08:36:20 GMT</pubDate>
            <atom:updated>2019-08-03T08:36:20.071Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aPRuHcAUSSrF_SE4.jpeg" /></figure><h3>Code Reuse</h3><p><strong><em>Reuse </em></strong>的中文翻譯是&quot;重用&quot;，而 <strong>Code Reuse </strong>對於工程師來說，就是將相似功能的程式碼重複利用；將會重複利用的 code 提出來，設計出一個通用的函式或是變數，藉此達到節省開發效率的目的。</p><p>下面這個例子用，function A 以及 function B 都有用一個簡單的 for 迴圈去計算陣列中，加總每一個數值的結果。可以看到可以看到 for 迴圈裡面做的事情非常類似，一個是單純的加總，另一個有對數值做一些運算後加總。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7511256a959445ddeeb5968df6883d57/href">https://medium.com/media/7511256a959445ddeeb5968df6883d57/href</a></iframe><p>如果我們可以將兩個 function 中的 for迴圈提出來，新增一個能夠依照設定的運算規則並且回傳加總後的數值，可以簡化兩個function 程式碼的結構，而且如果以後需要用到類似的功能就直接呼叫已經實作好的程式碼即可達到目的。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97340f3322a22f5d97fa73264a070625/href">https://medium.com/media/97340f3322a22f5d97fa73264a070625/href</a></iframe><p><strong><em>Code Reuse</em></strong> 這個行為，透過將程式碼中具有相同性質的部分提出來達到重複利用的功能，可以提昇軟體設計師在 coding 上的效率，以及提升程式的維護性。</p><h3>Code Reuse in React</h3><p>當我們在設計一個 <strong>React component</strong> 時，通常會考慮到需要從父層傳入哪些資料當作是 <strong><em>props</em></strong> 以及需要設計哪些 <strong><em>state</em></strong> 來控制component內部的狀態，最後是要如何呈現即將要設計 <strong>component</strong>。</p><p>以下是一個簡單的component，我們將name透過props傳入，並且設定一個state ages為26作為歲數，當使用者按下button就會將ages加一。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c942e523a4d51fa660b36ba6210ff2d/href">https://medium.com/media/7c942e523a4d51fa660b36ba6210ff2d/href</a></iframe><p>如果我們需要透過串接 API 的方式接取資料，我們可以把上述的程式碼更改成下面的寫法。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f77cdf7e22a18da2cab27fad18596d4c/href">https://medium.com/media/f77cdf7e22a18da2cab27fad18596d4c/href</a></iframe><p>我們將上面透過 props 傳入的 name 改成透過 Fetch 的方式，從 github API 接取使用者的資料，並且使用回傳資料中的 login 值印出 userID 。</p><p>然而，在實作上，我們經常會透過 Fetch 的方式向後端的資料庫接取我們需要的資料；如果每一個需要 Fetch 資料的 component 都需要在 component 內寫一份類似的 Fetch 方法，這將會非常的浪費時間。</p><p>因此我們可以透過React官方文件上提到的 <strong>higher-order component<em> </em></strong>來解決重複的程式碼產生。</p><h3>higher-order component(HOC)</h3><blockquote>React 官方文件提到：<br><a href="https://reactjs.org/docs/higher-order-components.html"><strong><em>A higher-order component (HOC) is an advanced technique in React for reusing component logic.</em></strong></a></blockquote><ul><li>一個component可以把傳進來的 props 資料傳換成 UI 介面或畫面。</li><li>一個 HOC 可以把一個 component 轉換成一個新的 component。</li></ul><p>HOC就很像是我們今天去買了一份麥當勞的套餐，我們選好套餐要的飲料還有薯條，店員會問你還要不要加點雞塊或是其他東西；之後我們就會加點這些東西，結果多花錢。</p><p>回到HOC的部分，如果已經實作出一個 Sample component可以渲染使用者的名字，而今天主管給了一個需求是要我們透過 Github API 回傳的資料，取出資料中的 name 來渲染出使用者的名字。</p><p>我們有兩個解決方案，一個是直接把 Sample component 修改成可已透過 Github API 取得使用者的名字，但是如果今天又有其他的component 也需要透過 Github API 取得資料，取得資料的這個方法就需要多寫幾次類似的程式碼了。(SampleByFetch.js)</p><p>另一個方案就是這篇文章提到的 higher-order component，我們可以是設計一個專門用來 fetch Github 上使用者的資料，並且將資料傳入 State ，作為Props 傳入 Sample。(如下程式碼)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16b78ac70bb354ea96af2608ba2515d4/href">https://medium.com/media/16b78ac70bb354ea96af2608ba2515d4/href</a></iframe><p>先介紹一下，為了這個例子設計的HOC元件，首先是參數值部分：</p><ol><li>Usecomponent → 顧名思義是用來傳遞準備要進行擴充的component，因此HOC會回傳一個component。</li><li>state → 在這個例子，state是要傳入此HOC 作為新的component的state。P.S. 此參數為非必要的參數。</li><li>useFunc → 同上 state ，為一個參數傳入此 HOC ，在此例子是用在componentDidMount時執行，在這個例子是要向 github 要求使用者資料，所以用async/await確保執行時不會遇到非同步問題。P.S. 此參數為非必要的參數。</li></ol><p>介紹完參數，我們可以著眼看一下一個 HOC 的程式碼結構，我們採用箭頭函式，傳入上述說的三個參數，接者回傳一個class component ；所以我們基本上也是在寫一個component，只是這個 component 會根據我們有可能會傳進來的 Usecomponent 進行擴充，也就是利用 componentDidMount 執行useFunc 的部分，以及在最後 JSX 新增了 &lt;div&gt;After HOC&lt;/div&gt; 此html element。</p><p>當我們設計完一個 HOC ，就可以運用他來擴充我們的比較基礎的 component 了；下面是一個基礎的 component 會簡單的印出 props 傳入的 name 資料。（如下面 Sample.js）</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/607c15fc76810d00387c4f9f17a310de/href">https://medium.com/media/607c15fc76810d00387c4f9f17a310de/href</a></iframe><p>接者我們可以使用我們的 HOC 來擴充我們的 Sample 了；看到下面的程式碼，在 index 裡我們引入了 HOC 以及 Sample，並且設計了一個 fetch方法來接取 github 上使用者的資料，所以我們把Sample、空的State以及fetchGit傳入HOC產生的新的compeonent，並且渲染他。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4b186ab3973f051948ee8c3f1961e35/href">https://medium.com/media/d4b186ab3973f051948ee8c3f1961e35/href</a></iframe><p>透過上面的流程， Sample 還是只能印出傳入 props 的 name 值，不過因為透過 HOC ，我們可以經由傳入的 useFeuc 來改變我們要傳入什麼資料進去 Sample，也就是說我們可以不用因為要接取 github 資料就寫一個 gitSample ，要接取 Facebook 資料就寫一個 fbSample；或是兩三個 component 接取的資料結構以及結果會是一樣的，卻因為呈現的結果不一樣，實作了兩三個compeonent，具有共通的 fetch 方法。</p><h3>Conclusion</h3><p>有了 Code Reuse 的概念之後，我們可以在設計 Function 時注意到哪些程式碼會在不同的地方重複利用，就可以將其提出來另外設計成泛用性較高的狀態，這樣在下次遇到相似狀況時就可以解省 Coding 的時間。</p><p>React 也是一樣的概念，我們可以把資料跟介面分開，介面的 component 就專心處理資料傳遞進來要如何呈現以及內部 Satae 要如何進行變化；而傳遞或接取資料的部分就可以提出來交給其他部分實作，因為這些方法可能還會在不同的 component 中用到，藉此達到 Code Reuse 的目的。</p><p>當然，不一定是只有在傳遞資料的時候才能用到 HOC 的概念，假如有一個按鈕會出現在很多 compoenent 裡，我們也可以將其提出來設計成 HOC ，如果以後再遇到相似的狀況就可以將直接套用此 HOC 。</p><p>只要有相同的部分，能夠將其提出並切設計成能夠泛用的形式，就叫做 Code Reuse ，而在 React 中 HOC 是一種比較高階的用法能夠達到 Code Reuse 的目的。</p><p>以上是我對於 Code Reuse 以及 React HOC 的一些想法以及看法，謝謝大家的收看，如果上述有哪些錯誤的想法以及論點，可以提出來一起研究或是討論，謝謝大家。</p><h3>相關資料</h3><ul><li><a href="https://medium.com/@soorajchandran/introduction-to-higher-order-components-hoc-in-react-383c9343a3aa">Introduction to higher-order components (HOC) in React</a></li><li><a href="https://medium.com/frochu/hoc-%E8%88%87renderprops-%E8%AB%87%E6%88%91%E5%BE%9E%E5%A5%B9%E5%80%91%E8%BA%AB%E4%B8%8A%E5%AD%B8%E5%88%B0%E4%BB%80%E9%BA%BC-2681ab4cc453">HOC 與RenderProps，談我從她們身上學到什麼</a></li><li><a href="https://cythilya.github.io/2018/05/20/react-hoc/">React.js: Higher-Order Components (HOC) | Summer。桑莫。夏天</a></li><li><a href="https://reactjs.org/docs/higher-order-components.html">Higher-Order Components - React</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15c457352fc4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lion-f2e/%E6%B7%BA%E8%AB%87high-order-component-hoc-15c457352fc4">淺談High Order Component(HOC)</a> was originally published in <a href="https://medium.com/lion-f2e">LT Lab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[About React “componentShouldUpdate ”& “Momo”]]></title>
            <link>https://medium.com/lion-f2e/about-react-componentshouldupdate-momo-8c4b5f5c57d3?source=rss-ceec4ab9674f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c4b5f5c57d3</guid>
            <category><![CDATA[componentshouldupdate]]></category>
            <category><![CDATA[memo]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Jian-Kai,Kuo]]></dc:creator>
            <pubDate>Sun, 21 Jul 2019 06:02:50 GMT</pubDate>
            <atom:updated>2019-07-21T06:07:04.084Z</atom:updated>
            <content:encoded><![CDATA[<h3>Talking about React “componentShouldUpdate<strong> </strong>”&amp; “<strong>Momo</strong>”</h3><h3>Component Lift-Cycle</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FTj1r3d4ABJch9yD" /><figcaption><a href="https://programmingwithmosh.com/javascript/react-lifecycle-methods/">https://programmingwithmosh.com/javascript/react-lifecycle-methods/</a></figcaption></figure><ol><li><strong><em>Mounting →</em></strong><em>元件被建立時被執行。</em></li><li><strong><em>Updating →</em></strong><em>父元件更新傳遞的props or 元件中更新state時執</em></li><li><strong><em>Unmounting</em></strong><em> →元件移除時執行。</em></li></ol><p><em>範例：父子元件執行lift-cycle 順序</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2F5kpvvkqx7k%3Ffontsize%3D14&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2F5kpvvkqx7k%3Ffontsize%3D14&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F5kpvvkqx7k%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/b9fd53e736086743bdf642f746c57047/href">https://medium.com/media/b9fd53e736086743bdf642f746c57047/href</a></iframe><ul><li><em>Mounting: 簡單講就是父元件先執行到render後，再來開始執行子元件的Mounting生命週期，最後執行完子元件的componentDidMount後，再回頭執行父元件的componentDidMount。</em></li><li><em>Updating: 父元件執行到render後，換子元件執行直到getSnapshotBeforeUpdate，會再回父元件執行getSnapshotBeforeUpdate，然後再執行子元件的componentDidUpdate，再回父元件執行componentDidUpdate。</em></li><li><em>UnMounting: 父元件先執行componentWillUnmount，再來是子元件執行。</em></li></ul><blockquote>引用至：<a href="https://iandays.com/2018/07/27/reactlife/index.html">https://iandays.com/2018/07/27/reactlife/index.html</a></blockquote><h3><strong>componentShouldUpdate(</strong>nextProps, nextState<strong>)</strong></h3><ul><li><em>nextProps → component下一個Props值</em></li><li><em>nextState → component下一個state值</em></li><li><em>return → 回傳true 會從新渲染組件，false則不會從新渲染。</em></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fc9258a6da39434be1e3f262ce990b3/href">https://medium.com/media/6fc9258a6da39434be1e3f262ce990b3/href</a></iframe><p><em>如果沒有shouldComponentUpdate檢查component是否要從新render，每當使用者點擊Button，React就會從新render此component。</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fsilly-hofstadter-o61hx%3Ffontsize%3D14&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fsilly-hofstadter-o61hx%3Ffontsize%3D14&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fo61hx%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/5add50e95379ae19020726c38c3babee/href">https://medium.com/media/5add50e95379ae19020726c38c3babee/href</a></iframe><p><em>在 </em><em>React v15.5 中新增了Pure Components，會自動檢查props以及state是否有更新，來判斷是否要從新渲染component 。因此不用在component中加入componentShouldUpdate的方法。</em></p><p><em>但是，在function component中無法使用componentShouldUpdate類似的方法能夠讓我們來控制component是否要從新渲染。</em></p><h3>React.memo(Component, areEqual)</h3><blockquote>React官方提到：<a href="https://reactjs.org/docs/react-api.html#reactmemo">React.memo</a> is a higher order component. It’s similar to React.PureComponent but for function components instead of classes.</blockquote><ul><li><em>Component → 使用者設計的function component。</em></li><li><em>areEqual → 讓React決定此component在父元件有props或是state更新時是否需要re-render。</em></li></ul><blockquote>React官方也提到，使用者可以自行設計需要的areEqual function，來判斷component是否需要re-render，areEqual 回傳true 表示props沒有變化無需re-render，false 則反之。預設是判斷props是否有更動。</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec330808bf715867c5fefb4846bf0110/href">https://medium.com/media/ec330808bf715867c5fefb4846bf0110/href</a></iframe><p><em>在上述程式碼中，當button被點擊時會觸發setCount將count中的值加一，觸發了 setState的機制，React會re-render App component，當中屬子元件的Text component也會跟著re-render；但是，同樣屬於子元件的MemoText component並不會同時re-render，React.Memo會比較component中props是不是有變化，來判斷是不是要re-render此component。</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Frelaxed-mcnulty-nqqrn%3Ffontsize%3D14&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Frelaxed-mcnulty-nqqrn%3Ffontsize%3D14&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fnqqrn%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/b76ae1136fe661eec46c3f8bff9f7827/href">https://medium.com/media/b76ae1136fe661eec46c3f8bff9f7827/href</a></iframe><blockquote>參考文件：</blockquote><blockquote><a href="https://reactjs.org/docs/react-api.html#reactmemo">https://reactjs.org/docs/react-api.html#reactmemo</a></blockquote><blockquote><a href="https://segmentfault.com/a/1190000018444604">https://juejin.im/post/5c8edf626fb9a0710d65c7fc</a></blockquote><blockquote><a href="https://segmentfault.com/a/1190000018444604">https://segmentfault.com/a/1190000018444604</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c4b5f5c57d3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lion-f2e/about-react-componentshouldupdate-momo-8c4b5f5c57d3">About React “componentShouldUpdate ”&amp; “Momo”</a> was originally published in <a href="https://medium.com/lion-f2e">LT Lab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>