React-用ImmutableJS提高性能

时间:2022-12-09 09:54:37

一、需求

1.子组件有更新时,只重新渲染有变化的子组件,而不是全部

二、ImmutableJS原理

React-用ImmutableJS提高性能

React-用ImmutableJS提高性能

三、代码

1.CheckboxWithLabel.jsx

 var React = require('react/addons');
var CheckboxWithLabel = React.createClass({
shouldComponentUpdate: function(nextProps, nextState) {
return nextProps.label !== this.props.label;
},
onChange: function() {
this.props.onChange(this.props.label.get("id"));
},
render: function() {
return (
<label>
{this.props.label.get("text")}
<input type = "checkbox" checked={this.props.label.get("checked")} onChange={this.onChange}/>
{this.props.label.get("checked") ? this.props.label.get("on") : this.props.label.get("off")}
</label>);
}
}); module.exports = CheckboxWithLabel;

2.SurveyList.jsx

 var React = require('react/addons');
var Immutable = require('immutable');
var CheckboxWithLabel = require('./CheckboxWithLabel.jsx') var SurveyList = React.createClass({
mixins: [React.addons.PureRenderMixin],
getInitialState: function() {
return Immutable.fromJS({
items: [
{
id: 0,
text: "你喜欢吃萝卜吗?",
on: "喜欢",
off: "不喜欢",
checked: false
},
{
id: 1,
text: "你喜欢吃西瓜吗?",
on: "喜欢",
off: "不喜欢",
checked: false
},
{
id: 2,
text: "你喜欢吃香蕉吗?",
on: "喜欢",
off: "不喜欢",
checked: false
}
]
});
},
onChange: function(labelId) {
var newState = this.state.setIn(["items", labelId, "checked"], !this.state.getIn(["items", labelId, "checked"]));
this.replaceState(newState);
},
render: function() {
var that = this;
return (
<div>
{
this.state.get("items").map(function(label) {
return <div><CheckboxWithLabel label={label} onChange={that.onChange.bind(that)}></CheckboxWithLabel></div>
})
}
</div>);
}
}); module.exports = SurveyList;

3.app.jsx

 var React = require('react/addons');
var SurveyList = require('./SurveyList.jsx'); React.render(<SurveyList></SurveyList>, document.body);
Perf = React.addons.Perf;

四、运行结果

React-用ImmutableJS提高性能