Thinking in React Implemented by Reagent

简介:

前言

 本文是学习Thinking in React这一章后的记录,并且用Reagent实现其中的示例。

概要

  1. 构造恰当的数据结构
  2. 从静态非交互版本开始
  3. 追加交互代码

一、构造恰当的数据结构

Since you’re often displaying a JSON data model to a user, you’ll find that if your model was built correctly, your UI (and therefore your component structure) will map nicely.

 VDom让我们可以将Model到View的映射交出,而更专注于数据和数据结构本身,即是折腾数据和数据结构才是我们的主要工作。因此我们要设计出与View中组件结构对应的数据结构,然后将不符合该数据结构的数据做一系列转换,然后将数据交给React就好了。
居上所述那么可以知道,数据结构就依赖View的结构,那么如何设计View的结构呢?是采用Top-down还是Bottom-up的方式呢?对于小型应用我们直接采用Top-down即可,对于大型应用则采用Bottom-up更合适。(根据过往经验将大规模的问题域拆分成多个小规模的问题域,然后对小问题域采用Top-down方式,若无法直接采用Top-down方式则继续拆分,然后将多个小问题域的值域组合即可得到大问题域的值域)
无论是Top-down还是Bottom-up方式,都要将View构建为树结构(这很符合DOM结构嘛)。因此得到如下结构

FilterableProductTable
|_SearchBar
|_ProductTable
  |_ProductCategoryRow
  |_ProductRow
AI 代码解读

 而数据则从顶层View组件往下流动,各层提取各自数据进行渲染。

二、从静态非交互版本开始

It’s best to decouple these processes because building a static version requires a lot of typing and no thinking, and adding interactivity requires a lot of thinking and not a lot of typing.

 从设计(他人或自己)那得到设计稿或HTML模板,我们就可以开始着手重构模板、添加交互效果和填充业务逻辑和服务端交互等功能了。且慢,我们先不着急动手,而是要先分清工作步骤,才能有条不紊地包质保量工作哦!

  1. 目标:得到符合React规范的View结构
  2. 目标:得到最低标准的可交互的React应用
  3. 目标:补充业务逻辑,细化交互
  4. 目标:连接远程数据源,细化交互
(ns demo.core
  (:require [reagent.core :as re])

(def products [
  {:category "Sporting Goods", :price "$49.99", :stocked true, :name "Football"}
  {:category "Sporting Goods", :price "$9.99", :stocked true, :name "Baseball"}
  {:category "Sporting Goods", :price "$29.99", :stocked false, :name "Basketball"}
  {:category "Electronics", :price "$99.99", :stocked true, :name "iPod Touch"}
  {:category "Electronics", :price "$399.99", :stocked false, :name "iPhone 5"}
  {:category "Electronics", :price "$199.99", :stocked true, :name "Nexus 7"}
])


(declare <filterable-product-table>
         <search-bar>
         <product-table>
         <product-category-row>
         <product-row>)

(declare get-rows)

(defn <filterable-product-table>
  [products]
  [:div
    [<search-bar>]
    [<product-table> products]])

(defn <search-bar>
  []
  [:form
    [:input {:placeholder "Search..."}]
    [:input {:type "checkbox"}]
    "Only show products in stock."])

(defn <product-table>
  [products]
  [:table
    [:thead
      [:tr
        [:th "Name"]
        [:th "Price"]]]
    [:tbody
      (get-rows products)]])

(defn assemble-rows
  [products]
   (reduce
    (fn [{:keys [cate] :as rows-info} product]
      (let [curr-cate (:category product)
            curr-rows (if (not= curr-cate cate)
                        (list ^{:key curr-cate}[<product-category-row> curr-cate])
                        (list))
            rows (cons ^{:key (:name product)} [<product-row> product] curr-rows)]
        (-> rows-info
          (assoc :cate curr-cate) ;; 更新cate值
          (update
            :rows
            (fn [o rows]
              (concat rows o))
            rows)))) ;; 更新rows值
    {:cate nil :rows '()}
    products))

(defn get-rows
  [products]
  (-> (assemble-rows products)
    :rows
    reverse))

(defn <product-category-row>
  [cate]
  [:tr
    [:td {:colSpan 2} cate]])

(defn <product-row>
  [product]
  [:tr
    [:td (when (:stocked product) {:style {:color "red"}})
      (:name product)]
    [:td (:price product)]])
AI 代码解读


这一步我们并没有提供交互功能,因此只会用到prop传递数据,绝对不会用到state的。而交互的意思是,对View的操作会影响应用数据,从而刷新View。

三、追加交互代码

 交互实质上就是触发View状态变化,那么就必须提供一种容器来暂存当前View的状态,而这个在React就是state了。

(ns demo.core
  (:require [reagent.core :as re])

(def products [
  {:category "Sporting Goods", :price "$49.99", :stocked true, :name "Football"}
  {:category "Sporting Goods", :price "$9.99", :stocked true, :name "Baseball"}
  {:category "Sporting Goods", :price "$29.99", :stocked false, :name "Basketball"}
  {:category "Electronics", :price "$99.99", :stocked true, :name "iPod Touch"}
  {:category "Electronics", :price "$399.99", :stocked false, :name "iPhone 5"}
  {:category "Electronics", :price "$199.99", :stocked true, :name "Nexus 7"}
])


(declare <filterable-product-table>
         <search-bar>
         <product-table>
         <product-category-row>
         <product-row>)

(declare get-rows
         validate-product)


(defn <filterable-product-table>
  [products]
  (let [search-text (re/atom "")
        stocked? (re/atom false)
        on-search-text-change #(reset! search-text (.. % -target -value))
        on-stocked?-change #(reset! stocked? (.. % -target -checked))]
    (fn []
      [:div
        [<search-bar> on-search-text-change on-stocked?-change]
        [<product-table> (filter (partial validate-product @search-text @stocked?) products)]])))

(defn validate-product
  [search-text stocked? product]
  (and (if stocked? (:stocked product) true)
       (as-> search-text %
         (re-pattern (str "(?i)" %))
         (re-find % (:name product)))))

(defn <search-bar>
  [on-search-text-change on-stocked?-change]
  [:form
    [:input {:placeholder "Search..."
             :onChange on-search-text-change}]
    [:input {:type "checkbox"
             :onChange on-stocked?-change}]
    "Only show products in stock."])

(defn <product-table>
  [products]
  [:table
    [:thead
      [:tr
        [:th "Name"]
        [:th "Price"]]]
    [:tbody
      (get-rows products)]])

(defn assemble-rows
  [products]
   (reduce
    (fn [{:keys [cate] :as rows-info} product]
      (let [curr-cate (:category product)
            curr-rows (if (not= curr-cate cate)
                        (list ^{:key curr-cate}[<product-category-row> curr-cate])
                        (list))
            rows (cons ^{:key (:name product)} [<product-row> product] curr-rows)]
        (-> rows-info
          (assoc :cate curr-cate) ;; 更新cate值
          (update
            :rows
            (fn [o rows]
              (concat rows o))
            rows)))) ;; 更新rows值
    {:cate nil :rows '()}
    products))

(defn get-rows
  [products]
  (-> (assemble-rows products)
    :rows
    reverse))

(defn <product-category-row>
  [cate]
  [:tr
    [:td {:colSpan 2} cate]])

(defn <product-row>
  [product]
  [:tr
    [:td (when (:stocked product) {:style {:color "red"}})
      (:name product)]
    [:td (:price product)]])
AI 代码解读

注意:reagent中使用state时,需要定义一个返回函数的高阶函数来实现。

(defn <statefull-cmp> [data]
  (let [local-state (re/atom nil)
        on-change #(reset! local-state (.. % -target -value))]
    (fn []
      [:div
        [:input {:onChange on-change}]
        [:span @local-state]])))

(re/render [<statefull-cmp> 1]
           (.querySelector js/document "#app"))
AI 代码解读

总结

 尊重原创,转载请注明转自:http://www.cnblogs.com/fsjohnhuang/p/7692956.html ^_^肥仔John

参考

https://reactjs.org/docs/thinking-in-react.html

如果您觉得本文的内容有趣就扫一下吧!捐赠互勉!

 
本文转自 ^_^肥仔John博客园博客,原文链接: http://www.cnblogs.com/fsjohnhuang/p/7692956.html /,如需转载请自行联系原作者
相关文章
kde
|
3天前
|
Docker镜像加速指南:手把手教你配置国内镜像源
配置国内镜像源可大幅提升 Docker 拉取速度,解决访问 Docker Hub 缓慢问题。本文详解 Linux、Docker Desktop 配置方法,并提供测速对比与常见问题解答,附最新可用镜像源列表,助力高效开发部署。
kde
1993 6
2025年最新版最细致Maven安装与配置指南(任何版本都可以依据本文章配置)
本文详细介绍了Maven的项目管理工具特性、安装步骤和配置方法。主要内容包括: Maven概述:解释Maven作为基于POM的构建工具,具备依赖管理、构建生命周期和仓库管理等功能。 安装步骤: 从官网下载最新版本 解压到指定目录 创建本地仓库文件夹 关键配置: 修改settings.xml文件 配置阿里云和清华大学镜像仓库以加速依赖下载 设置本地仓库路径 附加说明:包含详细的配置示例和截图指导,适用于各种操作系统环境。 本文提供了完整的Maven安装和配置
2025年最新版最细致Maven安装与配置指南(任何版本都可以依据本文章配置)
Dify MCP 保姆级教程来了!
大语言模型,例如 DeepSeek,如果不能联网、不能操作外部工具,只能是聊天机器人。除了聊天没什么可做的。
555 4
国内如何安装和使用 Claude Code镜像教程 - Windows 用户篇
国内如何安装和使用 Claude Code镜像教程 - Windows 用户篇
359 0
Excel数据治理新思路:引入智能体实现自动纠错【Python+Agent】
本文介绍如何利用智能体与Python代码批量处理Excel中的脏数据,解决人工录入导致的格式混乱、逻辑错误等问题。通过构建具备数据校验、异常标记及自动修正功能的系统,将数小时的人工核查任务缩短至分钟级,大幅提升数据一致性和办公效率。
【保姆级图文详解】大模型、Spring AI编程调用大模型
【保姆级图文详解】大模型、Spring AI编程调用大模型
199 5
【保姆级图文详解】大模型、Spring AI编程调用大模型
让AI时代的卓越架构触手可及,阿里云技术解决方案开放免费试用
阿里云推出基于场景的解决方案免费试用活动,新老用户均可领取100点试用点,完成部署还可再领最高100点,相当于一年可获得最高200元云资源。覆盖AI、大数据、互联网应用开发等多个领域,支持热门场景如DeepSeek部署、模型微调等,助力企业和开发者快速验证方案并上云。
245 17
让AI时代的卓越架构触手可及,阿里云技术解决方案开放免费试用
DeepSeek R1+Open WebUI实现本地知识库的搭建和局域网访问
本文介绍了使用 DeepSeek R1 和 Open WebUI 搭建本地知识库的详细步骤与注意事项,涵盖核心组件介绍、硬件与软件准备、模型部署、知识库构建及问答功能实现等内容,适用于本地文档存储、向量化与检索增强生成(RAG)场景的应用开发。
298 0
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等

登录插画

登录以查看您的控制台资源

管理云资源
状态一览
快捷访问