React:无法根据 If 语句导入模块:对象作为 React 子项无效(已找到:[object Promise])

React: Cannot Import a Module Based on an If Statement: Objects are not valid as a React child (found: [object Promise])

我正在尝试根据 if 条件在 React 中导入一个模块。我读过 import 语句 returns 一个承诺。但是,我找不到解决这个问题的方法。当我静态导入模块时代码有效,但它不适用于动态导入:

list.js

// import WelcomeGuide from './guide'; //this one works
const show_deprecated_guide = '';

const WelcomeGuide = (props) => ( // this one throws an error
    import(`${!show_deprecated_guide ? `./guide.js` : `./guide-deprecated.js`}`)
        .then( (Module) => (
            Module.default
        )
        )
        .catch ((err) => (
            console.log(err)
        )
    )
)

const WelcomeList = (props) => {

    // loading state..
    if (!posts) return <div className="guide-list"><Spinner /></div>;


    // loaded state
    return (
        <Fragment>
                <WelcomeGuide/>
        </Fragment>
    )
};

export default WelcomeList;

guide.js

const WelcomeGuide = (props) => {

  return (
    <p>Welcome!</p>
  )
}

export default WelcomeGuide;

我知道我可以静态导入这两个组件并有条件地渲染它们,但是如果我可以根据我拥有的数据导入它们似乎对性能更好。所以,我的问题是:如何在使用 if 语句时正确导入模块?我阅读了很多教程,我知道错误是不言自明的,但我仍然无法解决这个问题。任何帮助将不胜感激!

我不是 100% 肯定理解您的问题,但我会说您需要导入两个指南并在渲染上使用条件:

import Guide from './...'
import DeprecatedGuide from './...'

const WelcomeList = ({ show_deprecated_guide }) => {
  return (
    <div>
      { show_deprecated_guide ? <DeprecatedGuide /> : <Guide /> }
    </div>
  )
}

这绝对不是你在 React 中渲染组件的方式。

如果这是可行的,它应该看起来像:

const WelcomeGuide = (props) => ( // this one throws an error
    import(show_deprecated_guide ? './guide.js' : './guide-deprecated.js')
        .then((Module) => (<Module />))
        .catch ((err) => {
            console.log(err)
        }
    )
)

此外,react 已经有解决方案来做这样的事情。它作为一个效用函数出现:lazy

要在这种情况下使用它,您可以执行以下操作:

const Guide = React.lazy(() => import('./guide.js'));
const GuideDeprecated = React.lazy(() => import('./guide-deprecated.js'));
const WelcomeGuide = (props) => (
    <Suspense fallback={<div>Loading...</div>}>
        show_deprecated_guide ? (<Guide />) : (<GuideDeprecated />)
    </Suspense>
)

请注意在延迟加载组件周围使用 Suspense。您可以 Suspense 在树的更上层,它仍然有效。

阅读有关代码拆分的更多信息here