Start with a mock
先来看一个简单设计
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, yourUI
(and therefore your component structure) will map nicely.(由于您经常向用户显示JSON
数据模型,您会发现如果您的模型正确构建,您的UI
(因此您的组件结构)将会很好地映射。) - That's because
UI
anddata models
tend to adhere to the same information architecture, which means the work of separating yourUI
into components is often trivial. Just break it up into components that represent exactly one piece of your data model.(这是因为UI和数据模型倾向于遵循相同的信息体系结构,这意味着将UI划分为组件是徒劳无功的。只将其划分为 完全代表一种数据模型 的组件即可)
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(
,
);
}
});
var SearchBar = React.createClass({
render:function(){
return(
);
}
});
var ProductTable = React.createClass({
render:function(){
var rows=[];
var lastCategory = null;
this.props.products.forEach(function(product){
if(product.category !== lastCategory){
rows.push();
}
rows.push( );
lastCategory = product.category;
});
return(
Name
Price
{rows}
);
}
});
var ProductCategoryRow = React.createClass({
render:function(){
return(
{this.props.category}
);
}
});
var ProductRow = React.createClass({
render:function(){
var name = this.props.product.stocked?
this.props.product.name:
{this.props.product.name}
;
return(
{name}
{this.props.product.price}
);
}
});
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(
,
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 (
);
}
});
var SearchBar = React.createClass({
render: function() {
return (
);
}
});
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( );
}
rows.push( );
lastCategory = product.category;
}.bind(this));
return (
Name
Price
{rows}
);
}
});
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(
,
);
}
});
var SearchBar = React.createClass({
handleChange:function(){
this.props.onUserInput(
this.refs.filterTextInput.value,
this.refs.inStockOnlyInput.checked
);
},
render:function(){
return(
);
}
});
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();
}
rows.push( );
lastCategory = product.category;
}.bind(this));
return(
Name
Price
{rows}
);
}
});
var ProductCategoryRow = React.createClass({
render:function(){
return(
{this.props.category}
);
}
});
var ProductRow = React.createClass({
render:function(){
var name = this.props.product.stocked?
this.props.product.name:
{this.props.product.name}
;
return(
{name}
{this.props.product.price}
);
}
});
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(
,
document.getElementById('content')
);