【发布时间】:2016-04-23 02:54:54
【问题描述】:
我在应用程序中使用 react+flux。我正在尝试使用不可变的 js 来加快渲染过程,因为每次我对状态进行任何小的更改时,react 都会尝试协调所有 DOM(这很慢)。
我遇到的问题是在我的 store.js 中,我可以将我的状态转换为不可变的 Map 对象。但是,一旦这个对象被传递给应用程序,它就不再被识别为 Map 对象,而只是一个普通对象。这意味着我不能使用 Map 对象附带的任何 set 或 get 函数
这是我目前所拥有的:
Store.js
var Immutable = require("immutable");
var Store = function(){
var jsState = { object1 : "state of object 1",
object2 : "state of object 2"}
this.globalState = Immutable.fromJS(globalState);
this._getGlobalState = function(){
//console will log: Map { size=2, _root=ArrayMapNode, __altered=false, more...}
//this.globalState.get("object1"); will work
console.log(this.globalState);
return this.globalState;
}
}
App.js
var Store = require("./Store.js");
var Map = require("immutable").Map
var App = React.createClass({
getInitialState: function(){
return ({});
},
componentWillMount: function()
this._getStateFromStore(); //will get the immutable state from the store
},
_getStateFromStore: function()
{
return this.setState(Store._getGlobalState());
},
render: function(){
//this will return Object { size=2, _root=ArrayMapNode, __altered=false, more...}
//this.state.get("object1") will NOT work
console.log(this.state);
return <div>This is in App</div>
}
});
我在这里做错了吗?我是否缺少任何文件中的任何模块?非常感谢!
【问题讨论】:
-
直接创建
Immutable.Map会更快:var jsState = Immutable.Map({ object1 : "state of object 1", object2 : "state of object 2"})而不是使用fromJS。此外,您还需要一个componentShouldUpdate方法来利用不可变的优势。查看PureRenderMixin是一种简单的方法。
标签: javascript immutability reactjs-flux immutable.js