简体   繁体   中英

React setState using ES6 Closures

I am totally new to React and ES6, and not able to understand how to apply the concept of closure here to update my state. I am working on a react app which uses Draftjs. I need to create a new map of (depth:[...text]) and store it in the component state to refer it later.

Following is my function to do that:

 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());
    });
}

First I am saving the current editorstate's blockMap(it is a draftjs map for getting block-level info in the editor). I am successful till this point.

Then i declare a new map and try to store k,v from the blockMap into depthMap using a .forEach() function.

Unfortunately, neither the state is getting updated, nor the depthMap is storing any data after running a forEach() over it.

I think I am going wrong here with the concept of closure or maybe something else.

React setState() method takes a javascript object. You should use it like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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