翻译--Thinking in React

前端之家收集整理的这篇文章主要介绍了翻译--Thinking in React前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

无聊翻译篇react入门文章,去年学习react时看了一遍,很不错的一篇文章

https://reactjs.org/docs/thin...

部分为意译,旨在让newcomers 容易理解。

()内均为译者注

React会是我快速构建大型webapp的首要js框架选择。
其在FacebookInstagram上的实践给予了我们充足的自信。

React众多闪光点中的一个就是让你开始思考如何设计、构建应用。(主要就是react是数据驱动设计,所以如何设计state成了很重要的一部分)

本文,将以一个商品下拉列表加搜索框的例子来展示react


Start With A Mock
本例子大概长这样,数据源来自构建的一个mock,以json api方式进行访问。

mock的json数据:

  1. [
  2. {category: "Sporting Goods",price: "$49.99",stocked: true,name: "Football"},{category: "Sporting Goods",price: "$9.99",name: "Baseball"},price: "$29.99",stocked: false,name: "Basketball"},{category: "Electronics",price: "$99.99",name: "iPod Touch"},price: "$399.99",name: "iPhone 5"},price: "$199.99",name: "Nexus 7"}
  3. ];

第一步:拆分组件,分析组件结构

译者注:组件结构拆分没有一个标准,例子里是拆的很细,实际工作中一般是统一规范较重要,可读性至上。

首先拆分成多个组件跟子组件,并且命名。这里已经用虚线框标识了。工作中,如何有设计或者产品辅助你的话,这个工作可能不需要你来做,交给他们即可。他们会用ps以图层的方式拆分好组件。(大厂吗?!)

这里的组件是已经拆分好了,但是如果自己拆分,该如何做呢?答案是用一定的标准进行规范。比如你可以选择的一个标准就是:单一职责原则。即一个组件只负责一件事情。(这个事情范围就广了,比如一个动作,一个请求。原则就是方便管理与维护)如果还能细分,就再拆成更小层次的组件。(react就是一层层组件嵌套,各种组件与子组件)

我们一般经常用json data model 返回给用户,在react中,只要data model格式正确,界面ui(组件)就渲染得很舒服了,一般相差不到哪儿去。这是因为uidata model 倾向于遵循相同的架构。跟这些带来的好处相比,拆分组件的基础工作就显得微不足道了。把界面打散拆分成多个组件,每个组件代表data model的某一部分。(这一大段啥意思呢?就是夸了一下react数据驱动的好处)

看上图,我们把ui拆成了5个组件,下面是各个组件对应的职责,斜体突出表示下。
1.FilterableProductTable(orange):contains the entirety of the example
(包裹所有子组件的外壳)
2.SearchBar(blue):处理用户交互
3.ProductTable(green):用户交互后过滤出的商品列表数据展示
4.ProductCategoryRow(turquiso 亮青色):显示商品列表分类名称
5.ProductRow(red):展示每个商品信息

这边注意观察下组件ProductTable下有两个label作为header--“Name”“Price”。这两个label没有作为单独的组件如ProductCategoryRowProductRow存在,这里仅仅是作为ProductTable的一部分存在。当然你可以将其作为单独一个子组件开辟出来,只是在这个例子里没必要,如果这个header再复杂一点,比如加上点击排序功能,那么可以再建一个子组件--ProductTableHeader

现在ui已经拆分完成,来分一下组件层次。
(其实就是个树状图,很多情况下,你的json data model 长啥样,组件层次基本上就差不离了)

·FilterableProductTable

  1. ·SearchBar
  2. ·ProductTable
  3. ·ProductCategoryRow
  4. ·ProductRow

(小问题,上面提到的ProductTableHeader如果存在,应该放在树状图的哪个位置呢?)

第二步:构建静态页面

  1. class ProductCategoryRow extends React.Component {
  2. render() {
  3. const category = this.props.category;
  4. return (
  5. <tr>
  6. <th colSpan="2">
  7. {category}
  8. </th>
  9. </tr>
  10. );
  11. }
  12. }
  13.  
  14. class ProductRow extends React.Component {
  15. render() {
  16. const product = this.props.product;
  17. const name = product.stocked ?
  18. product.name :
  19. <span style={{color: 'red'}}>
  20. {product.name}
  21. </span>;
  22.  
  23. return (
  24. <tr>
  25. <td>{name}</td>
  26. <td>{product.price}</td>
  27. </tr>
  28. );
  29. }
  30. }
  31.  
  32. class ProductTable extends React.Component {
  33. render() {
  34. const rows = [];
  35. let lastCategory = null;
  36. this.props.products.forEach((product) => {
  37. if (product.category !== lastCategory) {
  38. rows.push(
  39. <ProductCategoryRow
  40. category={product.category}
  41. key={product.category} />
  42. );
  43. }
  44. rows.push(
  45. <ProductRow
  46. product={product}
  47. key={product.name} />
  48. );
  49. lastCategory = product.category;
  50. });
  51.  
  52. return (
  53. <table>
  54. <thead>
  55. <tr>
  56. <th>Name</th>
  57. <th>Price</th>
  58. </tr>
  59. </thead>
  60. <tbody>{rows}</tbody>
  61. </table>
  62. );
  63. }
  64. }
  65.  
  66. class SearchBar extends React.Component {
  67. render() {
  68. return (
  69. <form>
  70. <input type="text" placeholder="Search..." />
  71. <p>
  72. <input type="checkBox" />
  73. {' '}
  74. Only show products in stock
  75. </p>
  76. </form>
  77. );
  78. }
  79. }
  80.  
  81. class FilterableProductTable extends React.Component {
  82. render() {
  83. return (
  84. <div>
  85. <SearchBar />
  86. <ProductTable products={this.props.products} />
  87. </div>
  88. );
  89. }
  90. }
  91.  
  92.  
  93. const PRODUCTS = [
  94. {category: 'Sporting Goods',price: '$49.99',name: 'Football'},{category: 'Sporting Goods',price: '$9.99',name: 'Baseball'},price: '$29.99',name: 'Basketball'},{category: 'Electronics',price: '$99.99',name: 'iPod Touch'},price: '$399.99',name: 'iPhone 5'},price: '$199.99',name: 'Nexus 7'}
  95. ];
  96. ReactDOM.render(
  97. <FilterableProductTable products={PRODUCTS} />,document.getElementById('container')
  98. );

现在组件拆分好了,json data model有了,开始实现界面代码吧。先做一个最简单的版本,只有界面,没有交互。交互留到后面做,这样分开做的好处是先做静态界面只用堆代码而不需要考虑逻辑交互,交互逻辑到后面做。(事情一件件做,也正符合组件拆分的标准之一,single responsibility principle,单一职责)

实现静态版本从构建组件开始,实现构建复用的基础之一就是通过使用props。何谓props?props就是将数据从树状图由上到下传递的快递员。(或者说从parent到child,这个parent或child是相对的,针对不同的两个组件,随时变化的,所以用树状图来理解舒服点)如果你有一定的react基础,熟悉state的话,(state也能传递数据)在这里先不要考虑用state,只有在交互的时候,随时间变化的数据需要用到state。

你可以从上到下或者由下至上构建组件,意思就是你可以先构建最上面的FilterableProductTable或者最下面的ProductRow。在简单的项目中,一般从上到下构建组件更简单。大点稍微复杂点的项目中可以由下至上构建组件,这样也方便编写测试实例。(简单例子怎样都行,复杂的项目,都是一个个组件嵌套的,缺什么补什么,一般不存在思考这个,除非整个项目是由你来从零架构的)

现在我们已经构建了一组可用于渲染data mod的复用组件构成的组件库。每个组件内只有一个方法render(),因为现在还只是静态页面。树状图最上端的组件FilterableProductTable会把data model 打包成一个props。如果你对data model进行更改并再次调用ReactDom.render(),ui界面就会更新。代码很简单,很容易观察ui如何更新以及在哪里进行更改。React另一个特性:单向数据流(也叫单项绑定 one way binding)使代码模块化且运行快速

小注:Props vs State

react中有两类存储data model的对象,props跟state。了解两者的区别还是很重要的。
详细:【?】https://reactjs.org/docs/inte...

第三步:定义完整而简洁的state

交互就是ui界面能对data model 的变化作出相应。React通过state使其实现变得简单。

继续构建app前,需要确定好完整且简洁的state。遵循的规则就是:DRY(don't repeat yourself)。举个例子,在做TODO List例子时,我们一般会用到List Count这个属性,但没必要将Count作为state的一个字段存在,因为通过计算List的length也能获取到Count。(只保留必要的属性字段在state中)

针对我们的应用,现有的数据如下:
a·原始商品列表数据
用户输入搜索文本
c·复选框选中与否
d·过滤后的商品列表数据

那么如何确定以上哪些是应该作为state的部分而存在的呢?可以简单的问问自己下面这三个问题:

1.该数据是通过props传递的吗?如果是,那就应该不属于state
2·该数据不是实时变化(即不随交互而变化)的,那就应该不属于state
3·可以通过其他state跟props计算而出(如上面说的List Count),那就应该不属于state

然后带着这三个问题,我们来看看上面四个数据。静态页面版本中已经看出,a是通过props传递的,所以a不属于state,b跟c是根据用户输入来确定的,随交互而变化,所以bc应该属于state的一部分,d可以通过abc结合计算而得,所以虽然会变化但也不属于state。

总结,state:
·用户输入文本
·复选框选中与否

  1. state =
  2. filterText''
  3. isStockOnlyfalse

第四步:构建state

  1. class ProductCategoryRow extends React.Component {
  2. render() {
  3. const category = this.props.category;
  4. return (
  5. <tr>
  6. <th colSpan="2">
  7. {category}
  8. </th>
  9. </tr>
  10. );
  11. }
  12. }
  13.  
  14. class ProductRow extends React.Component {
  15. render() {
  16. const product = this.props.product;
  17. const name = product.stocked ?
  18. product.name :
  19. <span style={{color: 'red'}}>
  20. {product.name}
  21. </span>;
  22.  
  23. return (
  24. <tr>
  25. <td>{name}</td>
  26. <td>{product.price}</td>
  27. </tr>
  28. );
  29. }
  30. }
  31.  
  32. class ProductTable extends React.Component {
  33. render() {
  34. const filterText = this.props.filterText;
  35. const inStockOnly = this.props.inStockOnly;
  36.  
  37. const rows = [];
  38. let lastCategory = null;
  39.  
  40. this.props.products.forEach((product) => {
  41. if (product.name.indexOf(filterText) === -1) {
  42. return;
  43. }
  44. if (inStockOnly && !product.stocked) {
  45. return;
  46. }
  47. if (product.category !== lastCategory) {
  48. rows.push(
  49. <ProductCategoryRow
  50. category={product.category}
  51. key={product.category} />
  52. );
  53. }
  54. rows.push(
  55. <ProductRow
  56. product={product}
  57. key={product.name}
  58. />
  59. );
  60. lastCategory = product.category;
  61. });
  62.  
  63. return (
  64. <table>
  65. <thead>
  66. <tr>
  67. <th>Name</th>
  68. <th>Price</th>
  69. </tr>
  70. </thead>
  71. <tbody>{rows}</tbody>
  72. </table>
  73. );
  74. }
  75. }
  76.  
  77. class SearchBar extends React.Component {
  78. render() {
  79. const filterText = this.props.filterText;
  80. const inStockOnly = this.props.inStockOnly;
  81.  
  82. return (
  83. <form>
  84. <input
  85. type="text"
  86. placeholder="Search..."
  87. value={filterText} />
  88. <p>
  89. <input
  90. type="checkBox"
  91. checked={inStockOnly} />
  92. {' '}
  93. Only show products in stock
  94. </p>
  95. </form>
  96. );
  97. }
  98. }
  99.  
  100. class FilterableProductTable extends React.Component {
  101. constructor(props) {
  102. super(props);
  103. this.state = {
  104. filterText: '',inStockOnly: false
  105. };
  106. }
  107.  
  108. render() {
  109. return (
  110. <div>
  111. <SearchBar
  112. filterText={this.state.filterText}
  113. inStockOnly={this.state.inStockOnly}
  114. />
  115. <ProductTable
  116. products={this.props.products}
  117. filterText={this.state.filterText}
  118. inStockOnly={this.state.inStockOnly}
  119. />
  120. </div>
  121. );
  122. }
  123. }
  124.  
  125.  
  126. const PRODUCTS = [
  127. {category: 'Sporting Goods',name: 'Nexus 7'}
  128. ];
  129.  
  130. ReactDOM.render(
  131. <FilterableProductTable products={PRODUCTS} />,document.getElementById('container')
  132. );

现在state已经确定好了,开始要与组件交互关联了,知道state的那部分应该放在哪个组件中。

再提醒一句:React是单向数据流导向的,从树状图的上端往下。

哪个组件应该有怎样的state对于react新手来讲可能是很困惑的一点,下面几点可能对你会有帮助:

·确定哪些组件在渲染过程中要用到state
·可能多个组件同时需要用到state的一部分,那边找到一个它们共同的parent component,把state放在这个组件里
·如果已有的组件中找不到这样的parent component,那就创建一个。
(意译)

依照以上标准分析下我们的应用:
·ProductTable 显示过滤后的商品数据,这需要通过state跟原始数据(在props中),SearchBar需要显示过滤文本跟复选框勾选情况。
·上面两者的common parent component就可以是FilterableProductTable。
·所以讲state中的filterText跟checkvalue放在FilterableProductTable,没毛病。

我们state中也就这两,所以放在哪个组件也确定了,开始码代码了。
首先,在FilterableProductTable中的构造函数里初始化state对象,然后将state里的内容作为props传递到对应的child component中去(交互=》触发预先定义的事件=》state变化=》作为state内容载体的props传递到对应组件=》具体组件render=》用户看到交互结果)

第五步:实现交互事件(add inverse data flow ,难以描述)

  1. class ProductCategoryRow extends React.Component {
  2. render() {
  3. const category = this.props.category;
  4. return (
  5. <tr>
  6. <th colSpan="2">
  7. {category}
  8. </th>
  9. </tr>
  10. );
  11. }
  12. }
  13.  
  14. class ProductRow extends React.Component {
  15. render() {
  16. const product = this.props.product;
  17. const name = product.stocked ?
  18. product.name :
  19. <span style={{color: 'red'}}>
  20. {product.name}
  21. </span>;
  22.  
  23. return (
  24. <tr>
  25. <td>{name}</td>
  26. <td>{product.price}</td>
  27. </tr>
  28. );
  29. }
  30. }
  31.  
  32. class ProductTable extends React.Component {
  33. render() {
  34. const filterText = this.props.filterText;
  35. const inStockOnly = this.props.inStockOnly;
  36.  
  37. const rows = [];
  38. let lastCategory = null;
  39.  
  40. this.props.products.forEach((product) => {
  41. if (product.name.indexOf(filterText) === -1) {
  42. return;
  43. }
  44. if (inStockOnly && !product.stocked) {
  45. return;
  46. }
  47. if (product.category !== lastCategory) {
  48. rows.push(
  49. <ProductCategoryRow
  50. category={product.category}
  51. key={product.category} />
  52. );
  53. }
  54. rows.push(
  55. <ProductRow
  56. product={product}
  57. key={product.name}
  58. />
  59. );
  60. lastCategory = product.category;
  61. });
  62.  
  63. return (
  64. <table>
  65. <thead>
  66. <tr>
  67. <th>Name</th>
  68. <th>Price</th>
  69. </tr>
  70. </thead>
  71. <tbody>{rows}</tbody>
  72. </table>
  73. );
  74. }
  75. }
  76.  
  77. class SearchBar extends React.Component {
  78. constructor(props) {
  79. super(props);
  80. this.handleFilterTextChange = this.handleFilterTextChange.bind(this);
  81. this.handleInStockChange = this.handleInStockChange.bind(this);
  82. }
  83. handleFilterTextChange(e) {
  84. this.props.onFilterTextChange(e.target.value);
  85. }
  86. handleInStockChange(e) {
  87. this.props.onInStockChange(e.target.checked);
  88. }
  89. render() {
  90. return (
  91. <form>
  92. <input
  93. type="text"
  94. placeholder="Search..."
  95. value={this.props.filterText}
  96. onChange={this.handleFilterTextChange}
  97. />
  98. <p>
  99. <input
  100. type="checkBox"
  101. checked={this.props.inStockOnly}
  102. onChange={this.handleInStockChange}
  103. />
  104. {' '}
  105. Only show products in stock
  106. </p>
  107. </form>
  108. );
  109. }
  110. }
  111.  
  112. class FilterableProductTable extends React.Component {
  113. constructor(props) {
  114. super(props);
  115. this.state = {
  116. filterText: '',inStockOnly: false
  117. };
  118. this.handleFilterTextChange = this.handleFilterTextChange.bind(this);
  119. this.handleInStockChange = this.handleInStockChange.bind(this);
  120. }
  121.  
  122. handleFilterTextChange(filterText) {
  123. this.setState({
  124. filterText: filterText
  125. });
  126. }
  127. handleInStockChange(inStockOnly) {
  128. this.setState({
  129. inStockOnly: inStockOnly
  130. })
  131. }
  132.  
  133. render() {
  134. return (
  135. <div>
  136. <SearchBar
  137. filterText={this.state.filterText}
  138. inStockOnly={this.state.inStockOnly}
  139. onFilterTextChange={this.handleFilterTextChange}
  140. onInStockChange={this.handleInStockChange}
  141. />
  142. <ProductTable
  143. products={this.props.products}
  144. filterText={this.state.filterText}
  145. inStockOnly={this.state.inStockOnly}
  146. />
  147. </div>
  148. );
  149. }
  150. }
  151.  
  152.  
  153. const PRODUCTS = [
  154. {category: 'Sporting Goods',document.getElementById('container')
  155. );

目前为止,通过state,props已经构建好了我们的页面,现在实现交互事件。

React使用的单向数据流跟单向数据绑定使react的工作易于理解,虽然这相比双向绑定的确需要写多点代码。(使黑魔法不再神秘,react不需要黑魔法)

下面这段过程总结,我觉得还是我上面注解的那段拿过来:

  1. 交互=》触发预先定义的事件=》state变化=》作为state内容载体的props传递到对应组件=》具体组件render=》用户看到交互结果

(数据绑定体现在,state一旦发生变化,跟state关联的数据都将重现计算,而通过数据驱动的页面也将重新渲染。)

that's all

欢迎讨论~
感谢阅读~

个人公众号:

猜你在找的React相关文章