2017-10-26 6 views
0

저는 ReactJS로 프로젝트를 만들고 있고, 내가 작성한 로컬 JSON 파일을 읽으려고합니다.ReactJS 가져 오기()를 인식하지 못했습니다.

나는이처럼 보이는 app.js 파일이 있습니다

import React, {Component} from 'react'; 
import fetch from 'isomorphic-fetch' 
import './App.css'; 

class App extends Component { 

    getData() { 
     return fetch('./examples/test.JSON').then(response => { 
      return response.json(); 
     }); 
    } 

    componentDidMount() { 
     console.log(this.getData()); 
    } 

    render() { 
     return (
      ... 
     ); 
    } 
} 

수출 기본 앱을;

getData 함수는 JSON 파일을 반입하고 응답을 리턴하려고 시도합니다. 그러나 then() 함수 나 json() 함수는 인식되지 않습니다.

수입품이 있습니까? 나는 그들이 동형 매치에서 왔을 것이라고 생각했다.

+0

"인식되지 않음"이란 무엇을 의미합니까? 정의되지 않았다는 뜻인가요? 오류 메시지가 무엇입니까? –

답변

0

다른 파일에서 데이터 JSON 데이터를 가져 오려면 해당 파일에서 해당 JSON const를 직접 내보내고 해당 cont를 가져 와서 사용할 수 있습니다.

처럼 내보내기 파일에서 JSON

Test.js abc.js

Import json from "Test.js" 

Comsole.log(" a is ", json.A) 
// a is 1 

그리고 내가 동형 페치 API를 만들기 위해 사용되는 생각에서

export default const json = { 
A:1, b:2 
//...... 
} 

로컬 파일에 액세스하는 대신 호출하십시오. isomorphic-fetch 문서를 통해 읽기

1

, 당신은 README의 상단에 경고가 표시됩니다

당신은 당신의 자신의 ES6 약속 호환 polyfill을 가져와야한다, 나는 ES6-약속을 제안한다. 자신의 README에 제안으로 polyfill 포함

시도의 설치 및 :

require('es6-promise').polyfill();

require('isomorphic-fetch');

내 생각 엔이 .then 일을 할 것입니다.

-1

왜 axios를 사용하지 않습니까?

간단히 npm install --save axios

하여 프로젝트에 Axios의를 추가 한 다음이

.... 
import axios from 'axios'; 
.... 
async function getData(){ 
    const res = await axios.get('./examples/test.JSON'); 
    console.log(res); 
    return res; 
} 

render(){ 
    return(
     <div>{this.getData()}</div> 
    ) 
} 
0

당신은 무엇을 기대 하는가? console.log(this.getData())에서 데이터를 출력 할 것으로 예상되면 잘못된 가져 오기가 사용됩니다. response.json()의 결과는 약속이기 때문에 실제 데이터가 아니기 때문에 this.getData()의 결과는 여전히 약속입니다.다음과 같이 코드를 수정 : 당신은 그들이 response.json()의 결과를 소비하는 초 .then() 방법을 가지고 examples for isomorphic-fetch에서 볼 이유

componentDidMount() { 
    //console.log(this.getData()); 
    this.getData().then(jsonData => { 
     console.log(jsonData); 
    }); 
} 

이것은;

fetch('//offline-news-api.herokuapp.com/stories') 
    .then(function(response) { 
     if (response.status >= 400) { 
      throw new Error("Bad response from server"); 
     } 
     return response.json(); 
    }) 
    .then(function(stories) { 
     console.log(stories); 
    }); 
관련 문제