【问题标题】:How to dynamically import react module which is json data如何动态导入作为json数据的反应模块
【发布时间】:2021-08-28 13:52:30
【问题描述】:

我有这样的模块

const RecyclerView = [
{
    text: 'RecyclerView data',
},
{
    text: 'Codes data',
}

];

export default RecyclerView

当我像下面这样导入和映射数据时,我得到了结果

recycle Recycler查看数据 ...

import React from "react";
import accordion from "../pages/RecyclerView";
import Home from "./Home"
import TextComponent from "./TextComponent";

export default function DecisionActivity(props) {
    //let data = Contents;

    const {title, hasContent} = props

    if(hasContent){

        //console.log({title});
        //where title is === RecyclerView
        // and hascontent is bool
       
        accordion.map(item=>{
            console.log("recycle ", item.text);
        })

        return <TextComponent text={title}/>
    
    }

     return <Home/> 
      
}

我不想用这条线 从“../pages/RecyclerView”导入手风琴;

作为 RecyclerView(文件名是动态的,可能会有更多不同的名称 我会在 title 属性中加入组件,然后我想映射 Json 数据以从不同的组件创建我的动态 UI...

在这种情况下任何人都可以帮助我,不同的解决方案也可以提供帮助,但文件名(如 RecyclerView)应该是动态的。

提前致谢

【问题讨论】:

    标签: reactjs dynamic module components


    【解决方案1】:

    使用dynamic imports 可以帮助你,我不知道你想做什么,所以我不能给你一个示例代码,但那篇文章可以帮助你。只需考虑动态导入是异步的

    【讨论】:

    • O' 谢谢@KOseare 最后我可以使用您的链接link 解决这个问题
    【解决方案2】:
    finally I could solve this thing using [link](https://javascript.info/modules-dynamic-imports) 
    
    ```
    import(`../pages/${title}.js`)
            .then(obj=>{
                console.log("recycle then1 ", obj);
                let acc = obj.default;
                console.log("recycle then2 ", acc);
                acc.map(item=>{
                    console.log("recycle then3 ", item.text);
                })
            })
            .catch(err=>{
                console.log("recycle err ", err);
            });
    ```
    and I got the require result before I did the thing like this but I missed `let acc = obj.default;` this thing
    

    【讨论】:

      猜你喜欢
      • 2020-07-18
      • 2017-07-13
      • 2011-04-06
      • 2021-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-11
      • 2020-09-06
      相关资源
      最近更新 更多