Thinking in React 学习笔记

Start with a mock

先来看一个简单设计


Paste_Image.png

JSON API返回如下数据

[
  {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"}
];

And then 见证奇迹的时刻到了

Step 1: Break the UI into a component hierarchy(将UI划分为组件的层级结构)

F:But how do you know what should be its own component?(怎样划分一个组件)
Q:Just use the same techniques for deciding if you should create a new function or object. (是否需要创建一个新的函数或者对象)

  • One such technique is the single responsibility principle(单一责任原则), that is, a component should ideally only do one thing(一个组件应该理想的只做一件事). If it ends up growing, it should be decomposed into smaller subcomponents.
  • 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.(由于您经常向用户显示JSON数据模型,您会发现如果您的模型正确构建,您的UI(因此您的组件结构)将会很好地映射。)
  • That's because UI and data models tend to adhere to the same information architecture, which means the work of separating your UI into components is often trivial. Just break it up into components that represent exactly one piece of your data model.(这是因为UI和数据模型倾向于遵循相同的信息体系结构,这意味着将UI划分为组件是徒劳无功的。只将其划分为 完全代表一种数据模型 的组件即可

Paste_Image.png

You'll see here that we have five components in our simple app. I've italicized the data each component represents.
1.FilterableProductTable (orange): contains the entirety of the example
2.SearchBar (blue): receives all user input
3.ProductTable** (green)**: displays and filters the data collection based on user input
4.ProductCategoryRow (turquoise): displays a heading for each category
5.ProductRow (red): displays a row for each product

  • FilterableProductTable
  • SearchBar
  • ProductTable
    • ProductCategoryRow
    • ProductRow

Step 2: Build a static version in React

/**
 * Created by AngelaMa on 2017/2/6.
 */



var FilterableProductTable = React.createClass({
  render:function(){
    return(
      <div>
        <SearchBar />,
        <ProductTable products={this.props.products}/>
      </div>
    );
  }
});
var SearchBar = React.createClass({
  render:function(){
    return(
      <form>
        <input type="text" placeholder="Search..."/>
        <p>
          <input type="checkbox"/>
          {' '}
          Only show products in stock
        </p>
      </form>
    );
  }
});
var ProductTable = React.createClass({
  render:function(){
    var rows=[];
    var lastCategory = null;
    this.props.products.forEach(function(product){
      if(product.category !== lastCategory){
        rows.push(<ProductCategoryRow category={product.category} key={product.category}/>);
      }
      rows.push(<ProductRow product={product} key={product.name} />);
      lastCategory = product.category;
    });
    return(
      <table>
        <thead>
          <tr>
            <th>Name</th>
            <th>Price</th>
          </tr>
        </thead>
        <tbody>{rows}</tbody>
      </table>
    );
  }
});
var ProductCategoryRow = React.createClass({
  render:function(){
    return(
      <tr>
        <th colSpan="2">{this.props.category}</th>
      </tr>
    );
  }
});
var ProductRow = React.createClass({
  render:function(){
    var name = this.props.product.stocked?
      this.props.product.name:
      <span style={{color:'red'}}>
        {this.props.product.name}
      </span>;
    return(
      <tr>
        <td>{name}</td>
        <td>{this.props.product.price}</td>
      </tr>
    );
  }
});

var 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'}
];

ReactDOM.render(
  <FilterableProductTable products={PRODUCTS}/>,
  document.getElementById('content')
);

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.(最好解耦合这些进程,因为建立一个静态的版本需要大量的打字,没有思想,添加交互性需要大量的思考而不是打字。)
Props:props are a way of passing data from parent to child.
State:State is reserved only for interactivity, that is, data that changes over time.(State仅用于交互性,即随时间变化的数据)
In simpler examples, it's usually easier to go top-down, and on larger projects, it's easier to go bottom-up and write tests as you build.(在更简单的例子中,通常更容易从上到下,而在更大的项目中,更容易从底层向上和编写测试。)
React's one-way data flow (also called one-way binding) keeps everything modular and fast.(React的单项数据流保证了模块化和快速)

Step 3: Identify the minimal (but complete) representation of UI state

(识别UI状态的最小(但完整)表示)
Figure out the absolute minimal representation of the state your application needs and compute everything else you need on-demand. (识别你的应用需要的绝对最小表示,并且计算你需要的所有其他内容)
For example, if you're building a TODO list, just keep an array of the TODO items around; don't keep a separate state variable for the count.(例如,构建一个TODO List,只需要保留TODO项目的数组,不要为计数保留单独的状态变量)

Let's go through each one and figure out which one is state. Simply ask three questions about each piece of data:

  • Is it passed in from a parent via props? If so, it probably isn't state.(通过props从父进程而来?)
  • Does it remain unchanged over time? If so, it probably isn't state.(随时间保持不变?)
  • Can you compute it based on any other state or props in your component? If so, it isn't state.(根据组件中的)
    Step 4: Identify where your state should live
var FilterableProductTable = React.createClass({
  getInitialState: function() {
    return {
      filterText: '',
      inStockOnly: false
    };
  },
  render: function() {
    return (
      <div>
        <SearchBar
          filterText={this.state.filterText}
          inStockOnly={this.state.inStockOnly}
        />
        <ProductTable
          products={this.props.products}
          filterText={this.state.filterText}
          inStockOnly={this.state.inStockOnly}
        />
      </div>
    );
  }
});

var SearchBar = React.createClass({
  render: function() {
    return (
      <form>
        <input type="text" placeholder="Search..." value={this.props.filterText} />
        <p>
          <input type="checkbox" checked={this.props.inStockOnly} />
          {' '}
          Only show products in stock
        </p>
      </form>
    );
  }
});

var ProductTable = React.createClass({
  render: function() {
    var rows = [];
    var lastCategory = null;
    this.props.products.forEach(function(product) {
      if (product.name.indexOf(this.props.filterText) === -1 || (!product.stocked && this.props.inStockOnly)) {
        return;
      }
      if (product.category !== lastCategory) {
        rows.push(<ProductCategoryRow category={product.category} key={product.category} />);
      }
      rows.push(<ProductRow product={product} key={product.name} />);
      lastCategory = product.category;
    }.bind(this));
    return (
      <table>
        <thead>
          <tr>
            <th>Name</th>
            <th>Price</th>
          </tr>
        </thead>
        <tbody>{rows}</tbody>
      </table>
    );
  }
});

Step 5: Add inverse data flow(添加逆向数据流)

Let's think about what we want to happen. We want to make sure that whenever the user changes the form, we update the state to reflect the user input. Since components should only update their own state, FilterableProductTable will pass a callback to SearchBar that will fire whenever the state should be updated. We can use the onChange event on the inputs to be notified of it. And the callback passed by FilterableProductTable will call setState(), and the app will be updated.

var FilterableProductTable = React.createClass({
  getInitialState:function(){
    return{
        filterText:'',
        inStockOnly:false,

    };
  },
  handleUserInput:function(filterText,inStockOnly){
    this.setState({
      filterText:filterText,
      inStockOnly:inStockOnly
    });
  },
  render:function(){
    return(
      <div>
        <SearchBar
          filterText={this.state.filterText}
          inStockOnly={this.state.inStockOnly}
          onUserInput={this.handleUserInput}
        />,
        <ProductTable
          products={this.props.products}
          filterText={this.state.filterText}
          inStockOnly={this.state.inStockOnly}
        />
      </div>
    );
  }
});
var SearchBar = React.createClass({
  handleChange:function(){
    this.props.onUserInput(
      this.refs.filterTextInput.value,
      this.refs.inStockOnlyInput.checked
    );
  },
  render:function(){
    return(
      <form>
        <input type="text" placeholder="Search..." value={this.props.filterText} ref="filterTextInput" onChange={this.handleChange}/>
        <p>
          <input type="checkbox" checked={this.props.inStockOnly} ref="inStockOnlyInput" onchange={this.handleChange}/>
          {' '}
          Only show products in stock
        </p>
      </form>
    );
  }
});
var ProductTable = React.createClass({
  render:function(){
    var rows=[];
    var lastCategory = null;
    this.props.products.forEach(function(product){
      if (product.name.indexOf(this.props.filterText) === -1 || (!product.stocked && this.props.inStockOnly)) {
        return;
      }
      if(product.category !== lastCategory){
        rows.push(<ProductCategoryRow category={product.category} key={product.category}/>);
      }
      rows.push(<ProductRow product={product} key={product.name} />);
      lastCategory = product.category;
    }.bind(this));
    return(
      <table>
        <thead>
          <tr>
            <th>Name</th>
            <th>Price</th>
          </tr>
        </thead>
        <tbody>{rows}</tbody>
      </table>
    );
  }
});
var ProductCategoryRow = React.createClass({
  render:function(){
    return(
      <tr>
        <th colSpan="2">{this.props.category}</th>
      </tr>
    );
  }
});
var ProductRow = React.createClass({
  render:function(){
    var name = this.props.product.stocked?
      this.props.product.name:
      <span style={{color:'red'}}>
        {this.props.product.name}
      </span>;
    return(
      <tr>
        <td>{name}</td>
        <td>{this.props.product.price}</td>
      </tr>
    );
  }
});

var 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'}
];

ReactDOM.render(
  <FilterableProductTable products={PRODUCTS}/>,
  document.getElementById('content')
);

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,132评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,802评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,566评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,858评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,867评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,695评论 1 282
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,064评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,705评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,915评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,677评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,796评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,432评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,041评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,992评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,223评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,185评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,535评论 2 343

推荐阅读更多精彩内容

  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的阅读 13,433评论 5 6
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,380评论 0 23
  • 独处,是现在生活中不可避免得一个现象。很多人向往独处,越来越多优秀得妹子觉得谈恋爱太累,还不如一个人过,越来越多得...
    最大的虾米皮阅读 698评论 0 1
  • 这场对话没休止 无结果只是谁都无法料及幕布的宽度我多羡慕你的天真你说不见底的深渊与未触及的虚无终止吧然而你仍坚持不见
    花胆大阅读 154评论 0 2
  • 青春的路上怎能不彷徨 我们终究要奔向远方 却总是像迷途的羔羊 怎么也找不到方向 少年 请别悲伤 还有梦想陪你去流浪...
    Z周快阅读 128评论 2 1