programing

React에서 JSON 파일 가져오기

showcode 2023. 3. 6. 21:38
반응형

React에서 JSON 파일 가져오기

React가 처음이고 JSON을 Import하려고 합니다.DATA변수를 지정합니다.다음의 에러가 표시됩니다.

모듈 ".customData.json"을 찾을 수 없습니다.

누가 나 좀 도와줄래?내 핸드폰이 있으면 작동됩니다.DATA에 가변적인.index.js외부 JSON 파일에 있을 때는 그렇지 않습니다.

index.js
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import customData from './customData.json';
import Profile from './components/profile';
import Hobbies from './components/hobbies';

class App extends Component {
  render() {
    return (
      <div>
        <Profile name={this.props.profileData.name}imgUrl={this.props.profileData.imgURL} />
        <Hobbies hobbyList={this.props.profileData.hobbyList}/>
      </div>
    );
  }
}

ReactDOM.render(<App profileData={DATA}/>, document.querySelector('.container'));
hobbies.js
import React, {Component} from 'react';

var Hobbies = React.createClass({
  render: function(){
    var hobbies = this.props.hobbyList.map(function(hobby, index){
        return (<li key={index}>{hobby}</li>);
    });
    return (
        <div>
            <h5>My hobbies:</h5>
            <ul>
                {hobbies}
            </ul>
        </div>
    );
  } 
});

export default Hobbies;
profile.js
import React from 'react';

var Profile = React.createClass({
render: function(){
    return (
        <div>
            <h3>{this.props.name}</h3>
            <img src={this.props.imgUrl} />
        </div>
    )
  }
});

export default Profile
customData.json
var DATA = {    
    name: 'John Smith',
    imgURL: 'http://lorempixel.com/100/100/',
    hobbyList: ['coding', 'writing', 'skiing']
}

export default DATA

(데이터 및 구성용 이외의 코드용 가짜 .js 확장자를 추가하지 않고)를 사용하는 것이 좋습니다.json-loader모듈.를 사용한 적이 있는 경우create-react-app프로젝트의 골격을 설정하려면 모듈이 이미 포함되어 있으므로 json을 Import하기만 하면 됩니다.

import Profile from './components/profile';

답변은 더 많은 것을 설명해 줍니다.

이 오래된 밤...

즉, 서드파티 모듈에 아웃소싱하는 것이 아니라 require를 사용하여 require 콜의 일부로 해석 처리를 노드에 맡겨야 합니다.또, 설정이 방탄인 것도 주의할 필요가 있습니다.즉, 반환되는 데이터를 주의 깊게 체크할 필요가 있습니다.

다만, 간결하게 하기 위해서, 다음의 예를 검토해 주세요.

예를 들어, 앱의 루트에 다음과 같은 구성 파일 'admins.json'이 있다고 가정합니다.

admins.json
[{
  "userName": "tech1337",
  "passSalted": "xxxxxxxxxxxx"
}]

따옴표로 둘러싸인 키에 주의해 주세요."userName","passSalted"!

저는 다음과 같이 간단하게 파일로부터 데이터를 꺼낼 수 있습니다.

let admins = require('~/app/admins.json');
console.log(admins[0].userName);

이제 데이터가 입력되어 일반(또는 배열) 개체로 사용할 수 있습니다.

를 인스톨 하면,

import customData from '../customData.json';

더 간단하게 말하면

import customData from '../customData';

인스톨 하려면

npm install --save-dev json-loader

가장 간단한 접근방식은 다음과 같습니다.

// Save this as someJson.js
const someJson = {
  name: 'Name',
  age: 20
}

export default someJson

그리고나서

import someJson from './someJson'

생성된 React 17:create-react-app기본적으로는 json Import가 기능합니다.

import config from './config.json'

이 솔루션은 다음과 같습니다.- data.json 파일을 src에서 퍼블릭디렉토리로 이동했습니다.그런 다음 fetch API를 사용하여 파일을 가져옵니다.

fetch('./data.json').then(response => {
      console.log(response);
      return response.json();
    }).then(data => {
      // Work with JSON data here
      console.log(data);
    }).catch(err => {
      // Do something for an error here
      console.log("Error Reading data " + err);
    });

문제는 리액트 앱을 컴파일한 후 가져오기 요청이 실제로 리액트 앱의 공개 디렉토리인 URL "http://localhost:3000/data.json"에서 파일을 찾는다는 것입니다.그러나 유감스럽게도 컴파일 중에 react app data.json 파일은 src에서 퍼블릭디렉토리로 이동되지 않습니다.따라서 data.json 파일을 src에서 퍼블릭디렉토리로 명시적으로 이동해야 합니다.

JSON 파일을 .js 확장자로 저장하고 JSON이 같은 디렉토리에 있는지 확인하십시오.

// .json 파일의 이름을 .json으로 변경하고 src 폴더에 보관합니다.

json 개체를 변수로 선언합니다.

var customData = {
   "key":"value"
};

module.exports를 사용하여 내보내기

module.exports = customData;

필요한 컴포넌트에서 2개의 폴더를 반드시 백업합니다.

import customData from '../customData';

현재 리액트 빌드에서는 다음과 같이 Import하여 사용할 수 있습니다.

import jsonData from 'path/to/myJson.json'

export default DATA ★★★★★★★★★★★★★★★★★」module.exports = DATA

서드파티제 코드나 라이브러리를 사용하지 않고 이를 수행하는 방법은 여러 가지가 있습니다(권장).

첫 번째 정적 방법: .json 파일을 생성하여 react 컴포넌트 예시로 Import합니다.

제 파일 이름은 "filen.json"입니다.

{"example" : "my text"}

example.json 내의 예제 키는 향후 문제를 방지하기 위해 큰따옴표를 사용하는 데 유의할 수 있습니다.

리액트 컴포넌트 Import 방법

import myJson from "jsonlocation";

이렇게 아무데서나 쓸 수 있어요.

myJson.example

몇 가지 고려해야 할 사항이 있습니다.이 방법을 사용하면 페이지 맨 위에서 가져오기를 선언해야 하며 동적으로 가져올 수 없습니다.

JSON 데이터를 동적으로 Import하는 경우는 어떨까요?다국어 지원 웹 사이트의 예?

2 다이내믹한 방법

먼저 위의 예시와 똑같이 JSON 파일을 선언합니다.

이번에는 데이터를 다른 방법으로 Import합니다.

let language = require('./en.json');

이것도 같은 방법으로 접속할 수 있습니다.

동적 하중은 어디에 있습니까?

다음으로 JSON을 동적으로 로드하는 방법을 나타냅니다.

let language = require(`./${variable}.json`);

모든 JSON 파일이 같은 디렉토리에 있는지 확인합니다.

여기서는 첫 번째 예시와 같은 방법으로 JSON을 사용할 수 있습니다.

myJson.example

무엇이 바뀌었을까요?우리가 정말로 필요로 하는 유일한 것이기 때문에 수입하는 방식입니다.

이게 도움이 됐으면 좋겠어요.

var langs={
  ar_AR:require('./locale/ar_AR.json'),
  cs_CZ:require('./locale/cs_CZ.json'),
  de_DE:require('./locale/de_DE.json'),
  el_GR:require('./locale/el_GR.json'),
  en_GB:require('./locale/en_GB.json'),
  es_ES:require('./locale/es_ES.json'),
  fr_FR:require('./locale/fr_FR.json'),
  hu_HU:require('./locale/hu_HU.json')
}
module.exports=langs;

모듈로 요구합니다.

let langs=require('./languages');

안부 전해요

이것은 에서는 효과가 있었다.React 16.11.0

// in customData.js
export const customData = {
  //json data here
  name: 'John Smith',
  imgURL: 'http://lorempixel.com/100/100/',
  hobbyList: ['coding', 'writing', 'skiing']
}
// in index.js
import { customData } from './customData';

// example usage later in index.js
<p>{customData.name}</p>

저는 JSON 파일을 퍼블릭 폴더에 넣는 것만으로 충분했습니다.다음을 사용하여 js를 Import할 수 있습니다.

brain.loadData("exampleFile.json");

그것은 내가 추측하는 것만큼 간단하다.꼭 시도해 보세요.d

언급URL : https://stackoverflow.com/questions/39686035/import-json-file-in-react

반응형