【问题标题】:this.setState() is not re-renderingthis.setState() 没有重新渲染
【发布时间】:2018-01-28 03:14:13
【问题描述】:

我有以下代码 sn-p 呈现 D3Tree。 D3Tree 是 React 组件,contextmenu 在 React 外部。为了访问和设置 D3Tree 的状态,它被绑定到 D3Tree。现在在初始加载和右键单击和更改状态时,D3Tree 会重新渲染,但是在更改页面和重新加载 D3Tree 组件时,它不会在右键单击和更改状态时重新渲染contextmenu(contextmenu在 d3 函数中右键单击时调用 .on('contextmenu',contextmenu))。有人可以解释这种不受欢迎的行为以及要做什么。向下滚动代码。 (如果我重新加载 D3Tree 组件并右键单击节点,即使在 状态更改 时,它不会重新渲染)

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

【问题讨论】:

  • 您能否使用例如CodeSandbox 创建一个独立的示例?您在上面的 sn-p 中有几个不好的做法,但不足以说明问题出在哪里。

标签: javascript reactjs d3.js react-redux


【解决方案1】:

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

【讨论】:

  • contextmenu 是一个 JS 函数。它在 renderTree() 函数内部调用,该函数也是 JS 函数。如果我将它保存在 React Component 中,我将无法调用 contextmenu。我可以吗?
  • 在 react 组件中可以调用 contextmenu 函数。
  • 如果组件在内部,我如何从外部组件调用上下文菜单。
【解决方案2】:

进行类似contextmenu = contextmenu.bind(D3Tree) 的绑定。 您可以使用.call 方法调用contextmenu(它接受上下文作为第一个参数)

【讨论】:

  • 我必须在哪里绑定这个。我已经在构造函数中绑定了。对不对?
  • 你的班级不知道这个函数。将其绑定到课堂之外
  • 你可以将它移动到你的班级并在那里绑定
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-01
  • 1970-01-01
  • 2018-05-19
  • 2018-01-30
  • 2021-11-18
  • 2021-08-04
相关资源
最近更新 更多