【问题标题】:How to properly pass immutablejs object in flux如何正确传递 immutablejs 对象
【发布时间】: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


【解决方案1】:

因此,您实际上不能强制 State 对象成为不可变对象。相反,您必须在状态中存储不可变对象。

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

getInitialState: function(){
  return ({
    data: Immutable.Map({})
  });
},

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

Facebook has a good example repo on this subject.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-18
    • 2018-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多