在我的React App的根组件中,我有这个:
class App extends Component {
...
ComponentDidMount() {
window.addEventListener('resize', this.handleResize, false);
}
handleResize{
this.parentSize = {height: window.innerWidht - this.node.offsetLeft ..., width: ...};
this.forceUpdate();
}
render() {
<div ref="e=>this.node=e}>
<ChildComponent parentSize={this.ParentSize} />
</div>
}
}
Run Code Online (Sandbox Code Playgroud)
我注意到,当App组件通过setState或forceUpdate()重新渲染时,实际上会重新安装子组件(因此,每次更新都会调用componentWillUnmount,componentWillMount,componentDidMount)。我期望的行为是仅再次调用Child组件的render函数。我最近升级到了React-router 4.x,所以不确定是否与此相关。
有人可以告诉我这是否是设计使然?多次调用我的componentDidMount会导致一些问题,因为我尝试在其中读取数据,并且我不想在调整大小时一次又一次地执行该昂贵的操作。
更新:
我发现了此问题的可能原因。我有多个嵌套的组件,并且由于很难发布整个项目,所以有时很难发布导致问题的实际代码。但是我认为是这样的:
return (
<div className="app-view" style={style} ref={el=>this.node=el}>
<Switch>
<Route exact path='/' component={() => <Home store={store} />} />
<Route path='*' component={Error404} />
</Switch>
</div>
);
Run Code Online (Sandbox Code Playgroud)
在这里,我试图将道具传递给路线(React-router 4.x)中的组件,方法是提供创建主页的功能,该功能可能会在每次渲染时重新创建主页。
因此问题就变成了,如何在不重新生成Route内每个渲染页面的情况下传递道具?