我对React和ES6完全陌生,不知道如何在这里应用闭包的概念来更新我的状态。我正在开发一个使用Draftjs的react应用程序。我需要创建一个新的(depth:[...text])
映射,并将其存储在组件状态中,以便稍后引用。
下面是我执行此操作的函数:
saveDepthMap(){
let blockMap = this.state.editorState.getCurrentContent().getBlockMap();
var depthMap = new Map();
blockMap.forEach(k => {
let depth = k.getDepth();
let text = k.getText();
if(text.replace(/^\s+|\s+$/g, '') !== undefined){
console.log(depth, text);
if(!depthMap.has(depth)) depthMap.set(depth, [text]);
else depthMap.set(depth, depthMap.get(depth).concat([text]));
}
});
this.setState({
depthMap
}, () => {
console.log(this.state.depthMap, this.state.editorState.getCurrentContent().getBlockMap());
});
}
首先,我保存当前编辑器状态的blockMap(这是一个在编辑器中获取块级信息的draftjs映射)。在这一点上,我是成功的。
然后我声明一个新的映射,并尝试使用.forEach()
函数将k,v从blockMap
存储到depthMap
中。
不幸的是,状态没有更新,在运行forEach()
之后,depthMap也没有存储任何数据。
我认为我在闭包或其他方面的概念上错了。
发布于 2018-02-20 13:41:43
React setState()
方法接受一个javascript对象。您应该像这样使用它
this.setState({ depthMap: newDepthMap }) //considering the newly created is newDepthMap
https://stackoverflow.com/questions/48878467
复制相似问题