簡體   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