当状态改变时,子组件的道具不会更新

时间:2018-05-03 19:05:26

标签: javascript reactjs

我使用拖放来实例化反应类,但由于某种原因,父组件中的状态未传递给子组件。孩子甚至没有被重新渲染,尝试过shouldComponentUpdate和componentWillReceiveProps。

家长相关代码:

dragEnd(e) {
    e.preventDefault();
    let me = this;

    let el = (
        <Pie key={ Date.now() * Math.random() } yAxisData={ me.state.yAxisData } legendData={ me.state.legendData } />
    )

    this.setState({
        cells: this.state.cells.concat(el),
    });
}

因此,在drop上创建,然后渲染如下:

render() {
    <div className = { "insights-data" } onDrop={ this.dragEnd } onDragOver={ this.preventDefault }>
        { this.state.cells }
    </div>
}

所有这一切都运行正常,但是现在当我更改传递给this.state.yAxisData和/或this.state.legendData的数据时,它没有在子组件上调用render。

这里的子组件呈现:

    render() {
    return (
        <div className="insights-cell">
            <ReactECharts
                option={ this.create() }
                style={{ position: "absolute", top: 0, bottom: 0, left: 0, right: 0, height: "100%" }}
                theme="chalk"
                notMerge={ true }
            />
        </div>
    )
}

有什么想法吗?我想也许有一个有约束力的问题,但这似乎不是,因为我使用了我=这个。它甚至没有重新渲染子组件。

1 个答案:

答案 0 :(得分:2)

您已经在dragEnd函数中创建元素,方法是将props传递给它并将它们存储到数组中。因此,数组this.state.cells包含已声明元素的数组。因此它无法更新状态更改。您应该在每个渲染上渲染一个新的元素数组。

只需在this.state.cells中推送拖动元素的一些必要细节,然后在每个渲染上遍历此数组。

dragEnd(e) {
    e.preventDefault();

    let el = draggedElementType

    this.setState({
        cells: this.state.cells.concat(el),
    });
}

在渲染中,遍历此数组并返回所需的元素。

render() {
    <div className = { "insights-data" } onDrop={ this.dragEnd } onDragOver={ this.preventDefault }>
        { this.state.cells.map((cell, index) => {
           if (cell === "pie") {
           return (<Pie key={index} yAxisData={ me.state.yAxisData } legendData={ me.state.legendData } />);
           }
           else if (){...
        )}
    </div>
}
相关问题