React-用ImmutableJS提高性能
一、需求
1.子组件有更新时,只重新渲染有变化的子组件,而不是全部
二、ImmutableJS原理
三、代码
1.CheckboxWithLabel.jsx
1 var React = require('react/addons'); 2 var CheckboxWithLabel = React.createClass({ 3 shouldComponentUpdate: function(nextProps, nextState) { 4 return nextProps.label !== this.props.label; 5 }, 6 onChange: function() { 7 this.props.onChange(this.props.label.get("id")); 8 }, 9 render: function() { 10 return ( 11 <label> 12 {this.props.label.get("text")} 13 <input type = "checkbox" checked={this.props.label.get("checked")} onChange={this.onChange}/> 14 {this.props.label.get("checked") ? this.props.label.get("on") : this.props.label.get("off")} 15 </label>); 16 } 17 }); 18 19 module.exports = CheckboxWithLabel;
2.SurveyList.jsx
1 var React = require('react/addons'); 2 var Immutable = require('immutable'); 3 var CheckboxWithLabel = require('./CheckboxWithLabel.jsx') 4 5 var SurveyList = React.createClass({ 6 mixins: [React.addons.PureRenderMixin], 7 getInitialState: function() { 8 return Immutable.fromJS({ 9 items: [ 10 { 11 id: 0, 12 text: "你喜欢吃萝卜吗?", 13 on: "喜欢", 14 off: "不喜欢", 15 checked: false 16 }, 17 { 18 id: 1, 19 text: "你喜欢吃西瓜吗?", 20 on: "喜欢", 21 off: "不喜欢", 22 checked: false 23 }, 24 { 25 id: 2, 26 text: "你喜欢吃香蕉吗?", 27 on: "喜欢", 28 off: "不喜欢", 29 checked: false 30 } 31 ] 32 }); 33 }, 34 onChange: function(labelId) { 35 var newState = this.state.setIn(["items", labelId, "checked"], !this.state.getIn(["items", labelId, "checked"])); 36 this.replaceState(newState); 37 }, 38 render: function() { 39 var that = this; 40 return ( 41 <div> 42 { 43 this.state.get("items").map(function(label) { 44 return <div><CheckboxWithLabel label={label} onChange={that.onChange.bind(that)}></CheckboxWithLabel></div> 45 }) 46 } 47 </div>); 48 } 49 }); 50 51 module.exports = SurveyList;
3.app.jsx
1 var React = require('react/addons'); 2 var SurveyList = require('./SurveyList.jsx'); 3 4 React.render(<SurveyList></SurveyList>, document.body); 5 Perf = React.addons.Perf;
四、运行结果
You can do anything you set your mind to, man!