【问题标题】:Error, when dynamically import a react js module with webpack使用 webpack 动态导入 react js 模块时出错
【发布时间】:2020-02-16 03:10:02
【问题描述】:

我想动态导入一个 react js 模块。该模块不是组件,它是数据对象,所以我不能使用反应代码拆分。在webpack docs 中有一个带有承诺的示例。当我在 react 组件中这样使用它时,它会引发错误,因为该组件会在 promise 被解决之前尝试渲染。我想以这种方式导入,以防数据不存在,我可以提供默认数据。

const dataProps = import(`./dataObject.js`).then(data=> data);

...
 render() {
  <SomeComponente data={data} />
}

【问题讨论】:

    标签: reactjs webpack


    【解决方案1】:

    我认为最好的方法是:

    const dataProps = import(`./dataObject.js`); // Start the importing 
    
    class MyComponent extends React.Component {
    
        constructor(props) {
            super(props);
            this.state {
                data: null
            }
        }
    
        componentDidMount() {
            dataProps.then(data => this.setState({ data });
        }
    
        render() {
           if (this.state.data !== null) {
               return <SomeComponent data={this.state.data} />
           }
           return null;
        }
    }
    

    只有在导入完成后,你才会真正渲染任何东西

    【讨论】:

    • 谢谢,我试过了,但是虽然提供了一个catch bock它会抛出一个错误,导致应用程序崩溃:找不到模块:无法解析'
    猜你喜欢
    • 2022-07-20
    • 2020-07-25
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    • 2019-09-24
    • 1970-01-01
    • 1970-01-01
    • 2019-06-16
    相关资源
    最近更新 更多