繁体   English   中英

使用ES6闭包反应setState

[英]React setState using ES6 Closures

我对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从blockMapdepthMap

不幸的是,在状态上运行forEach()之后,状态既没有更新,也没有depthMap存储任何数据。

我认为我在这里用闭包或其他概念出错了。

React setState()方法采用一个javascript对象。 你应该这样使用

this.setState({ depthMap: newDepthMap }) //considering the newly created is newDepthMap  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM