如何在 flux 中正确传递不可变 js 对象

How to properly pass immutablejs object in flux

本文关键字:不可变 js 对象 flux      更新时间:2023-09-26

我在应用程序中使用react+flux。我正在尝试使用不可变的 js 来加快渲染过程,因为每次我对状态进行任何小的更改时,react 都会尝试协调所有 DOM(这很慢)。

我遇到的问题是,在我的商店.js内,我可以将我的状态转换为不可变的 Map 对象。但是,一旦此对象传递到应用,它就不再被识别为 Map 对象,而只是一个普通对象。这意味着我无法使用 Map 对象附带的任何集合或获取函数

这是我到目前为止所拥有的:

商店.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;
    }
}

应用.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>
    }
});

我在这里做错了什么吗?我是否缺少任何文件中的任何模块?非常感谢!

因此

,您实际上不能强制State对象是不可变的对象。相反,您必须将不可变对象存储在您的状态中。

因此,您需要执行以下操作:

getInitialState: function(){
  return ({
    data: Immutable.Map({})
  });
},
...
_getStateFromStore: function()
{
  return this.setState({
    data: Store._getGlobalState()
  });
},

Facebook在这个问题上有一个很好的例子。