一切正常,直到我运行一个方法将一些对象添加到存储中,这会触发 View 上的重新渲染...事情是在第一页中加载组件上的存储是一个包含其所有内容的 map 方法,更新后,当组件重新渲染时,它会丢失方法并变成普通的 js 对象,显然组件尝试执行 store.get() ,但失败了:S
这是一个屏幕截图:
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 方法上重新创建商店对象,结果相同。任何帮助/建议将不胜感激。谢谢
最佳答案
我最近也遇到了同样的问题,我认为如果计划修改对象的状态,您应该使用 mergeIn
而不是 setIn
。
检查这个jsbin相同的解释。
关于javascript - 不可变的js map 存储对象丢失方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38675076/