Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/apache-kafka/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在reactjs组件中动态加载json?_Reactjs - Fatal编程技术网

如何在reactjs组件中动态加载json?

如何在reactjs组件中动态加载json?,reactjs,Reactjs,url是动态的 url/:id/:名称(使用Reach路由器) 在文章组件中, 如果url为url/1/name1,我想加载1.json;如果url id为2,我想加载2.json import menuArray from '../data/menu.json'; 这就是我通常在reactjs中加载json的方式 class Article extends React.Component { constructor(props) { super(props);

url是动态的

url/:id/:名称(使用Reach路由器)

在文章组件中,
如果url为url/1/name1,我想加载1.json;如果url id为2,我想加载2.json

import menuArray from '../data/menu.json';
这就是我通常在reactjs中加载json的方式

class Article extends React.Component {
    constructor(props) { 
       super(props);
       if(/* id is available in the menuArray */) {
          //i want to load the json by id and store it in state
       }  
    } 
}

在reactjs中加载动态json文件的最佳解决方案是什么?

更好的方法是创建一个.js文件,然后使用const,例如:data.js

const navigation = [
    {
        navItemId: 1,
        navItemName: 'About Me',
        navItemPath: '/'
    }
];
export {navigation};
要使用它的文件,请使用以下代码:

import { navigation, bio, education } from './constants';
state = {navigation: navigation}

更好的方法是创建一个.js文件,然后使用const,例如:data.js

const navigation = [
    {
        navItemId: 1,
        navItemName: 'About Me',
        navItemPath: '/'
    }
];
export {navigation};
要使用它的文件,请使用以下代码:

import { navigation, bio, education } from './constants';
state = {navigation: navigation}

不确定这是否有用,但我最近建立了一个网站,我必须根据道具动态加载页面内容的降价文件:

const getMarkdown = async (page) => {
  const markdownFilePath = `./content/${page}.md`
  const markdownFile = await require(`${markdownFilePath}`)
  return markdownFile
}
然后在我的组件中,我将执行以下操作:

const introText = getMarkdown(page)
然后呈现
{introText}


您可以使用url参数中的id对json文件的异步请求执行相同的操作?

不确定这是否有任何用处,但我最近构建了一个站点,在该站点中,我必须根据道具动态加载页面中内容的标记文件:

const getMarkdown = async (page) => {
  const markdownFilePath = `./content/${page}.md`
  const markdownFile = await require(`${markdownFilePath}`)
  return markdownFile
}
然后在我的组件中,我将执行以下操作:

const introText = getMarkdown(page)
然后呈现
{introText}


您可以使用url参数中的id对json文件的异步请求执行相同的操作?

根据Reach路由器文档,url参数应作为道具提供?所以理论上你应该在你的文章里有一个props.id?是的。我可以从道具上获取id。但是如何在构造函数中导入json呢?根据Reach路由器文档,url参数应该可以作为道具使用?所以理论上你应该在你的文章里有一个props.id?是的。我可以从道具上获取id。但是如何在构造函数中导入json呢?我想这就是我想要的。我会在完成工作后分享我的评论。嗨@Mahesh只是想知道这是否最终对你有效?我想这就是我想要的。我会在完成工作后分享我的评论。嗨@Mahesh只是想知道这是否最终对你有效?