【发布时间】:2021-01-16 20:19:33
【问题描述】:
这里我试图在兄弟组件 A 和 B 之间传递数据,我想在组件 A 中的异步事件完成后重新渲染组件 B。
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
valueKey: '',
};
}
parentFunction(dataFromChild) {
this.setState({ valueKey: dataFromChild });
}
render() {
const { valueKey } = this.state;
return (
<div>
<componentA
url={url}
...
functionCallFromParent={() => this.parentFunction()}
/>
<componentB valueFromParent={valueKey} />
</div>
);
}
}
class componentA extends React.Component {
constructor(props) {
super(props);
this.state = {
items: null,
};
// asynchronous request made to server which updates the state when response received.
this._getTiles();
}
render() {
const { items } = this.state;
if (items && items.asArray().length > 0) {
functionCallFromParent('Hello From Child1');
return (
<div>
{tiles}
</div>
);
}
return null;
}
}
问题是,每次 componentA 调用 functionCallFromParent() ParentComponent 的渲染都会执行,它会重新渲染 componentA 和 componentB 并且这个循环继续。然而,我只希望在 componentA 要求时重新渲染 componentB。
【问题讨论】:
-
你应该在异步代码部分(大概是
_getTiles)中调用functionCallFromParent,而不是在渲染函数中 -
@maya_nk99 但我没有按钮单击或任何用户事件。组件 B 需要在组件 A 中发生的异步事件完成后重新渲染
-
如果 asArray() 是 Javascript 中的一个函数?我认为它是在 Python 中
-
每次设置状态时,都会导致使用该状态的组件重新渲染。所以它导致了无限循环。
标签: javascript reactjs react-redux jsx