javascript - 状态更改时子组件的道具不更新
问题描述
我正在使用拖放来实例化反应类,但由于某种原因,父组件的状态没有传递给子组件。孩子甚至没有被重新渲染,尝试过 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. 它甚至没有重新渲染子组件。
解决方案
您已经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>
}
推荐阅读
- angular - 如何在 Storybook 中使用相对角度分量?
- excel - 在 Excel 的 Power Query 中通过 ODBC 连接连接时选择要连接的架构
- r - 如何将标签添加到 R 中的点?- 示例不起作用
- r - 是否有一个带有通用类 data.frame 的 R 包,其中列可以是数组(或者我如何定义这样的类)?
- python - 根据另一列中的项目对 pandas 列中的值求和
- shodan - 在某些字段上输出 json 文件而不使用 Shodan 过滤数据?
- c++ - 在 C++ 中搜索和保护单链表
- excel - 在 VBA 中使用 Trim 获取长度代码需要帮助
- c++ - 从二维数组中获取前一个数组,其中给定数组作为函数中的参数传递
- spring - 当我尝试传递查询参数时,“/”被添加到我的重定向 URL