最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React component import static json file - Stack Overflow

programmeradmin2浏览0评论

I am importing a json file like this:

import React from 'react';
import Test1 from './test1.jsx';
import data from './data.json';


class TestWrapper extends React.Component {
  render () {
    return (
      <div>
        <h2>Projects</h2>
        <Test1 projects={data} />
      </div>
    );
  }
}

export default TestWrapper;

which I am then try to use it in:

import React from 'react';

class Test1 extends React.Component {
  render () {
    var rows = [];
    this.props.projects.map(function(el){
       rows.push(<p key={el}>{el}</p>);
    });
    return (
      <div>
        <h2>Test 1</h2>
        {rows}
      </div>
    );
  }
}

export default Test1;

this is my data.json

{
  "projects": [
    "title1",
    "title2",
    "title3",
    "title4"
  ]
}

I am getting the following error:

Uncaught TypeError: this.props.projects.map is not a function

do I need to parse my json file?

I am importing a json file like this:

import React from 'react';
import Test1 from './test1.jsx';
import data from './data.json';


class TestWrapper extends React.Component {
  render () {
    return (
      <div>
        <h2>Projects</h2>
        <Test1 projects={data} />
      </div>
    );
  }
}

export default TestWrapper;

which I am then try to use it in:

import React from 'react';

class Test1 extends React.Component {
  render () {
    var rows = [];
    this.props.projects.map(function(el){
       rows.push(<p key={el}>{el}</p>);
    });
    return (
      <div>
        <h2>Test 1</h2>
        {rows}
      </div>
    );
  }
}

export default Test1;

this is my data.json

{
  "projects": [
    "title1",
    "title2",
    "title3",
    "title4"
  ]
}

I am getting the following error:

Uncaught TypeError: this.props.projects.map is not a function

do I need to parse my json file?

Share Improve this question asked Aug 15, 2016 at 18:00 AessandroAessandro 5,78321 gold badges73 silver badges146 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

No, but this.props.projects will contain the JSON data, so you will need to do:

this.props.projects.projects.map

you have a projects property inside the json object {projects: []}. therefore you have to do this.props.projects.projects.map

Using ES6 destructuring you can retrieve and assign projects value from your json import.

import { projects } from './data.json';
发布评论

评论列表(0)

  1. 暂无评论