【问题标题】:Webpack dynamic import causing react remountWebpack动态导入导致react remount
【发布时间】:2018-08-24 11:52:04
【问题描述】:

版本

webpack 4.1.1、react 16.3.1、apollo-boost 0.1.4(apollo-client 2.2.8)

请参阅下面的代码。基本上我发现,每当我尝试在渲染函数中加载我的组件时,都会永远调用 componentDidMount。删除对 .default 的引用并仅渲染 null 即可解决问题,而将对 .default 的引用移动到 render 方法不会。我怎样才能在这里使用动态导入以及正确反应?请注意,在我使用 react-apollo 查询组件来管理状态之前,它运行良好。我需要做什么才能结合这 3 个工具来实际合作?在同一问题上 4-5 小时后,我没有取得任何进展。

const RouterContainer = () => (
  <Query
    query={gql`
      {
        currentRoute @client
        routeArgs @client
      }
    `}
  >{({ data }) => <Router {...data} />}</Query>
);

class Router extends React.Component {
  state = {
    component: null,
    page: '',
  }
  fetchComponent = () => {
    import('./MyComponent).then(Component => {
      this.setState({ Component: Component.default });
    });
  }
  static getDerivedStateFromProps(nextProps, prevState) {
    if (prevState.page !== nextProps.currentRoute) {
      return { page: nextProps.currentRoute };
    }
    return null;
  }
  componentDidMount() {
    // Being run infinitely. Why???
    // this.fetchComponent();
  }
  render() {
    return this.state.Component ? <this.state.Component /> : null;
  }
}

【问题讨论】:

  • 为什么需要做动态导入?为什么不直接导入并使用它?
  • 完全忘了早点发布我的答案。我误诊的无关问题。动态导入很大程度上是我正在使用的概念证明
  • 那么你应该删除这个问题。

标签: reactjs webpack react-apollo


【解决方案1】:

我打算在几个月前提出这个问题,但显然我没想到。问题最终与此无关,并且我所做的不完整的重构导致了无限的反应树(子渲染父)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-24
    • 2020-01-11
    • 2019-06-16
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多