首页 > 解决方案 > 如何更新“componentDidUpdate”中的 React 元素?

问题描述

我正在尝试渲染几个依赖于其他反应元素的 x 和 y 坐标的反应元素。我知道我必须更新“componentDidUpdate”方法中的元素,因为在渲染组件之前我无法获取值。

当前行为没有任何更新。renderNew 包含我想要渲染的反应元素,但它没有更新,因为没有显示任何内容。

我没有将值存储在状态中,我认为我不需要。

这是我设置状态和其他变量的地方

    constructor(props) {
        super(props);
        this.state = {
            priceDataData: jsonOrders.order.map(order => order.total),
            heightData: '',
            xElements: '',
            yElements: '',
            dotsWeWant: ''
        };
        this.dimensionsX = [];
        this.dimensionsY = [];
        this.renderNew = [];
        this.dotRef = [];
    }

这是我的 componentDidUpdate 方法

    componentDidUpdate = () => {

        const nodeRefs = this.dotRef;
        this.dimensionsX = this.connectTheDotsX(nodeRefs);
        this.dimensionsY = this.connectTheDotsY(nodeRefs);
        this.renderNew = this.renderNewLines(this.dimensionsX, 
        this.dimensionsY, this.state.priceDataData, this.state.dotsWeWant);

    }

    }

我的 JSX 的片段,其中包含未更新的变量。第一次渲染时它将为空,需要更新。

    <div className="graph_space">
       <div className="dot_container">
           {this.state.dotsWeWant}
       </div>
       <div className="test_stuff">
            {this.renderNew}
       </div>
    </div>

标签: javascriptreactjs

解决方案


推荐阅读