如何使用React延迟加载导入Json文件? [英] How to import Json file with React lazy loading?

查看:81
本文介绍了如何使用React延迟加载导入Json文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的React应用程序中实现延迟加载,但是大多数文件都是JSON.当视口宽度小于(例如)768像素,当不需要它们时,我不想将它们加载到桌面应用程序中.有什么方法可以使用React.lazy()加载JSON文件吗?

I want to implement lazy loading in my React app but most of the files are JSON. Few of them are loading when the viewport width is less than e.g. 768px and I don't want to load them in the Desktop app when they are not needed. Is there any way to load the JSON file with React.lazy()?

我的JSON文件是使用称为"Bodymovin"的Adobe After Effects扩展生成的,后来我像这样导入该文件:

My JSON file is generated with Adobe After Effect extensions called: 'Bodymovin' and later I am importing this file like this:

import * as background from './background.json';
import * as backgroundLarge from './background-large.json';
import * as backgroundMedium from './background-medium.json';
import * as backgroundMobile from './background-mobile.json';
import * as backgroundSmallMobile from './background-smallMobile.json';
import * as tree from './tree.json';
import * as treeLarge from './tree-large.json';
import * as treeMedium from './tree-medium.json';
import * as treeMobile from './tree-mobile.json';
import * as treeSmallMobile from './tree-smallMobile.json';

我试图像其他任何具有默认导出功能的组件一样正常加载它,但是它不起作用.

I was trying to load it normally like any other components with default export but it's not working.

const treeMedium = lazy(() => import('./tree-medium.json'));

当我正常导入JSON时,我以后会像这样使用它:

When I import JSON normally I am using it later like this:

backgroundOptions: {
      loop: true,
      autoplay: true,
      animationData: background.default,
    },

并将此对象从 react-lottie

我可以将其转换为延迟加载吗?还是我想错了?

Can I convert it to lazy loading or I am thinking wrong?

推荐答案

它不是React组件,因此您不应使用 lazy 调用包装它.
基本上,您只需要加载它并兑现承诺即可.
像这样:

It's not a React component, so you shouldn't wrap it with a lazy call.
Basically you just need to load it and handle a promise.
Something like:

componentDidMount() {
 import('./tree-medium.json').then(background => {
  this.setState({ background })
 })
}

,然后在您的 render

这篇关于如何使用React延迟加载导入Json文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆