reactjs - React 组件在页面刷新时构造了两次
问题描述
我有一些反应组件,我正在使用反应路由器进行路由。
在 App.js 中
componentDidMount() {
HttpService.get("masterData")
.then(response => {
this.setState({
masterData: response.data.masterData
})
.catch(e => {});
}
render() {
return (
<Router>
<Switch>
<Route
path="/viewAsset"
component= {()=> <ViewAssetComponent masterData={this.state.masterData}/> }
/>
//....
</Switch>
</Router>
)
}
但是我的 ViewAssetComponent 正在构建两次,并且 componentDidMount 也被调用了两次,这是意料之中的。
解决方案
此行为是由于您的react-router
Route 上的组件的呈现方法。
根据官方文档
当您使用组件道具时,路由器使用 React.createElement 从给定组件创建一个新的 React 元素。这意味着如果您为组件属性提供内联函数,您将在每次渲染时创建一个新组件。这会导致卸载现有组件并安装新组件,而不仅仅是更新现有组件。”</p>
当 App.js http 调用完成后,App.js 将重新渲染,这使得 react 路由器重新生成组件,因为路由的组件被定义为内联函数。该函数将被执行并<ViewAssetComponent/>
再次构造。
所以理想情况下,最好的方法是将带有 props 的组件放在 render props 的<Route/>
<Route
path="/viewAsset"
render={props => (
<ViewAssetComponent{...props} masterData={this.state.masterData} />
)}
/>
它将只构造一次组件。
推荐阅读
- ios - CoreData 一对一关系:重新启动应用程序后对象为零
- sendgrid - Sendgrid 是否按收件人向您收费?
- javascript - 禁用表单提交 JQuery 上的按钮后,使用按钮名称将表单提交给 PHP
- vb.net - 如何调整大小和图像并保存为字节数组
- javascript - 如何在不覆盖先前值的情况下将多个值设置为同一个键?
- vba - 在 VBA 中使用 2 个向量的元素创建消息
- android - 如何使用 Intent 在 kotlin 中放置数据类列表
- generics - 是否可以在 Rust 中编写通用整数长度函数?
- java - 如何用 Jackson 定义 2 级继承结构
- ios - 未在 viewController 中执行 Segue