首页 > 解决方案 > 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 也被调用了两次,这是意料之中的。

标签: reactjsreact-router

解决方案


此行为是由于您的react-routerRoute 上的组件的呈现方法。

根据官方文档

当您使用组件道具时,路由器使用 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} />
        )}
      />

它将只构造一次组件。


推荐阅读