【问题标题】:React setState using ES6 Closures使用 ES6 闭包反应 setState
【发布时间】:2018-07-30 09:56:30
【问题描述】:

我对 React 和 ES6 完全陌生,无法理解如何在这里应用闭包的概念来更新我的状态。我正在开发一个使用 Draftjs 的反应应用程序。我需要创建一个(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 也没有存储任何数据。

我认为我在闭包的概念或其他方面有问题。

【问题讨论】:

  • 你通过记录检查了blockMap。使用调试器很好地检查它
  • @RIYAJKHAN 我确实正确加载了blockMap。问题出在我想这里的闭包上..
  • @Herohtar 不是 ES6 语法吗?变量名相同的就不用:了?
  • @Omkar depthMap 在功能范围内声明。所以,不要认为访问它会出现问题
  • @Chris 不,异步代码不会神奇地乱序运行。 forEach 将在执行到达setState 调用之前同步执行。

标签: javascript reactjs ecmascript-6 closures draftjs


【解决方案1】:

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

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

【讨论】:

  • setState 使用正确,需要回调,检查stackoverflow.com/questions/42038590/…
  • @izengod 使用 newDepthmap 还是仅仅使用 depthMap 都没有关系,它是一种 ES6 语法糖,如果它与您所在州的变量匹配,则只需使用名称。
猜你喜欢
  • 2016-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-09
  • 2021-07-12
  • 2018-11-03
  • 1970-01-01
  • 2020-05-11
相关资源
最近更新 更多