简体   繁体   中英

this.setState() is not re-rendering

I have the following code snippet which renders a D3Tree. D3Tree is React Component and contextmenu is outside the React. In order to access and set the state of D3Tree, it is binded to D3Tree. Now on initial load and on right click and change of state , D3Tree re-renders, but on change of page and re-load of D3Tree Component, it does not re-render on right click and change of state by contextmenu (contextmenu is called on right-click in d3 function as .on('contextmenu',contextmenu) ). Can some one please explain this undesired behavior and what is that to be done. Scroll down for code. (If I re-load the D3Tree Component and right click on node it is not re-rendering even on state change )

export default class D3Tree extends BaseWidget {

    constructor(props)
    {
        super(props);
        this.state = {
            style_popup : {
                top : 90,
                left : 90,
                position : 'absolute'
            },
            render_on_click : false
        }
        contextmenu = contextmenu.bind(this);
    }

    componentDidMount(){
        var mountNode = ReactDom.findDOMNode(this.tree);


        // Render the tree usng d3 after first component mount
        if (this.props.treeData) {
            renderTree(this.props.treeData, mountNode, this.props.nodeName);
        }

    }

    shouldComponentUpdate(nextProps, nextState){

        var mountNode = ReactDom.findDOMNode(this.tree);
        // Delegate rendering the tree to a d3 function on prop change
        if (this.props.treeData != nextProps.treeData) {
            renderTree(nextProps.treeData, mountNode, this.props.nodeName);
        }



         return true;
    }

    render() {


        return (
            <div id="tree">
                <div id ="tree-container" ref={(tree) => { this.tree = tree; }}>

                </div>
                {
                (this.state.render_on_click) ? <div><PopUp popup_style = {this.state.style_popup} /></div> : null
                }
          </div>
        );
    }
}




function contextmenu(node)
{

        this.setState({
            style_popup : {
                top : d3.event.clientY,
                left : d3.event.clientX,
                position : 'absolute'
            },
            render_on_click : true
        });
}

上下文菜单函数在类之外,将其放在类内,然后将该函数绑定到构造函数中,如下所示:this.contextmenu = this.contextmenu.bind(this);

Make a bind like contextmenu = contextmenu.bind(D3Tree) . Either you can call contextmenu with .call method (which accepts context as first argument)

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