首页 > 解决方案 > 状态更改时子组件的道具不更新

问题描述

我正在使用拖放来实例化反应类,但由于某种原因,父组件的状态没有传递给子组件。孩子甚至没有被重新渲染,尝试过 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),
    });
}

所以,在放置时,创建,然后渲染看起来像:

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

所有这些工作正常,但是现在当我更改传递给 this.state.yAxisData 和/或 this.state.legendData 的数据时,它不会在子组件上调用渲染。

这是子组件的渲染:

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

有任何想法吗?我认为可能存在绑定问题,但似乎不是这样,因为我正在使用 me = this. 它甚至没有重新渲染子组件。

标签: javascriptreactjs

解决方案


您已经dragEnd通过将道具传递给它并将它们存储到数组中来创建函数中的元素。因此,该数组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>
}

推荐阅读