簡體   English   中英

React.js:如何使用源文件中index.js中加載的json數據?

[英]React.js: how to use json data that is loaded in index.js in source file?

所以這是index.js(我的入口點),我在這里加載json數據

import React from 'react';
import ReactDOM from 'react-dom';
import fetch from 'isomorphic-fetch';
import {Filter} from './src/filter';

fetch('./pizza.json')
    .then(function(response) {
        return response.json()
    }).then(function(json) {
    console.log('parsed json', json)
}).catch(function(ex) {
    console.log('parsing failed', ex)
});


ReactDOM.render(<Filter />, document.querySelector('.content'));

現在在要呈現頁面內容的filter.js中,我不確定如何在index.js中使用加載的數據,此處為filter.js

import React, {Component} from 'react';


export class Filter extends Component {
    render() {
        return (
            <div>
                    <h1> Pizza Search App </h1>

            </div>
        );
    }
}

我是React.js的新手,正在嘗試學習,但難以理解React.js的基本原理,有所幫助!

您應該在Filter進行提取

import React, { Component } from 'react';
import fetch from 'isomorphic-fetch';

export class Filter extends Component {

  state = {
    data: null
  }

  componentWillMount() {
    fetch('./pizza.json')
      .then(function (response) {
        return response.json()
      }).then(function (json) {
        console.log('parsed json', json)
        this.setState(() => ({ data: json }))
      }).catch(function (ex) {
        console.log('parsing failed', ex)
      });
  }

  render() {
    const { data } = this.state
    if(!data){
      return <div>Loading...</div>
    }
    return (
      <div>
        <h1> Pizza Search App </h1>
        (use data here...)
      </div>
    );
  }
}

亞歷克斯是正確的,除了您需要在收到響應后設置狀態:

編輯:我想念他在他的諾言鏈中還有另一個鏈接……無論哪種方式,您只需要一個。 像這樣:

componentWillMount() {
  fetch(...).then(res => this.setState({data: res.json()})).catch(....

另外,您需要對json進行“字符串化”,以便在組件的render方法中顯示它。 您無法顯示這樣的原始對象。 如此...您需要做類似的事情

...
render() {
  const { data } = this.state
  return (
    <div>
      <pre>
        <code>
          {JSON.stringify(data, null, 2)} // you should also look into mapping this into some kind of display component
        </code>
      </pre>
    </div>
  )
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM