我使用拖放来实例化 react 类,但由于某种原因,父组件的状态没有传递给子组件。 child 甚至没有被重新渲染,尝试了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>
)
}
有什么想法吗?我认为也许存在绑定(bind)问题,但似乎并非如此,因为我正在使用 me = this.它甚至没有重新渲染子组件。
最佳答案
您已经在 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>
}
关于javascript - 状态更改时子组件的 props 不会更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50162245/