不可变的js映射存储对象丢失方法

时间:2016-07-30 14:35:27

标签: javascript reactjs immutability flux

一切正常,直到我运行一个方法将一些对象添加到商店,即在视图上触发重新渲染...事情是在第一页加载组件上的商店是一个包含所有它的地图方法,在更新之后以及重新呈现组件时它会丢失方法并转换为普通的js对象,显然组件会尝试执行store.get()并且它会失败:S

这是截图:

a console log in the store and below a console log to the object on the react component 和一些代码:

class BlogStore {
  constructor() {
    this.bindListeners({
      handleBlogs: Actions.UPDATE_BLOGS,
      handleBlogPost: Actions.UPDATE_BLOG_POST,
      addMoreBlogs: Actions.ADD_MORE_BLOGS,
    });

    console.log('STORE: state before initialization', this.store);
    /* here is where the state structure is defined */
    this.state = Immutable.Map({
      blogs: {
        blogList: [],
        meta: {
          count: 0,
        },
        currentPage: 1,
      },
      blogPost: []
    });
  }

  /* here is where the state gets modified */
  addMoreBlogs(blogs) {
    console.log('addMoreBlogs executed');
    console.log('STORE: state before convertion to js', this.state);
    console.log('we have to add this to the store', blogs);

    //const currentPage = this.state.blogs.currentPage + 1;

    console.log('STORE: blogList should not be empty', this.state.get('blogs').blogList.concat(blogs.blogList));

    const updatedBlogs = this.state.get('blogs').blogList.concat(blogs.blogList);
    const updatedMeta = this.state.get('blogs').meta;

    console.log('STORE: updatedBlogs', updatedBlogs);
    console.log('STORE, updatedMeta', updatedMeta);

    this.setState(this.state.setIn(
      ['blogs'],
      {
        blogList: updatedBlogs,
        meta: updatedMeta,
        currentPage: 1,
      }
      ));

      console.log('STORE: updated state', this.state);
  }
  ...

和组件:

class BlogsWrapper extends React.Component {
  constructor(props) {
    super(props);

    /* get the store data and transform it to plain js */
    this.state = Store.getState();

    //console.log('BLOGSWRAPPER: state gotten in constructor:', this.state);
    this._onChange = this._onChange.bind(this);
  }

  componentDidMount() {
    Store.listen(this._onChange);

    // if (this.state.get('blogs').isEmpty()) {
    //   this.context.router.push('/blog/not-found');
    //   return;
    // }
  }

  componentWillUnmount() {
    Store.unlisten(this._onChange);

    //console.log('BLOGSWRAPPER: resetting page counter');
  }

  _onChange() {
    //this.setState(Store.getState().toJS());
    this.setState(Store.getState());
    console.log('BLOGSWRAPPER: onchange fired', this.state);
  }**

  ...

对此有何帮助?我无法弄清楚发生了什么,我还尝试在addMoreBlogs方法上创建具有相同结果的store对象。任何帮助/建议将不胜感激。感谢

2 个答案:

答案 0 :(得分:1)

我最近也遇到了同样的问题,如果我打算用对象修改状态,我认为你应该使用mergeIn而不是setIn

检查此jsbin是否有相同的解释。

答案 1 :(得分:1)

你可以试试这个:

this.setState(this.state.setIn(
  ['blogs'],
  Immutable.formJS({
    blogList: updatedBlogs,
    meta: updatedMeta,
    currentPage: 1,
  })));

显然,这是一个黑客攻击。使用不可变状态时,应避免以这种方式更新所有状态。相反,您需要更新您的可变对象的确切字段。这就是为什么来自Facebook的人建议尽可能让国家保持平稳。