2017-05-26 75 views
-1

我正在使用本地.json文件並在React中呈現它。這裏是我的代碼:想從外部JSON文件呈現API,但出現錯誤

import React from 'react'; 
import ReactDOM from 'react-dom'; 

class App extends React.Component { 
constructor(props) { 
    super(props); 
    this.setState = { tree: [] } 
} 

componentDidMount() { 
    $.get(this.props.source, function(result) { 
     var nodes; 
     nodes = result; 
     if (this.isMounted()) { 
      this.setState({ tree: nodes }); 
     } 
    }.bind(this)); 
} 

render() { 
    return (
     <div> 
      <h4>Results from ajax</h4> 
      {this.state.tree} //here i get json array 
      <h4>Tree</h4> 
      {this.state.tree.map(function(nodes) { 
       return <li key={nodes.hits.hits._score}>{nodes.hits.hits._id}</li> 
      })} 
     </div> 
     ); 
    } 
} 
export default App; 

現在我收到此錯誤:

./src/components/app.js 
Line 11: '$' is not defined no-undef 

Search for the keywords to learn more about each error. 

幫助我,請。我還嘗試在env中的package.json中配置ESLint,方法是轉換JQuery:true。

+0

使用NPM這樣

npm install jquery --save

進口的jQuery您必須手動輸入的jQuery中安裝jQuery。你可以使用'fetch()'這是默認方法來使api請求 –

+0

'{this.state.tree}'會產生錯誤,因爲反應無法打印對象。嘗試'{JSON.stringyfy(this.state.tree)}' –

+0

我個人更喜歡'axios'來在反應環境中做請求。 JQuery適用於dom操作和其他許多事情,但在使用React等UI框架時並不是必須的 – Icepickle

回答

0

您的組件

import $ from 'jquery' //In case of ES 6 

var $ = require('jquery'); //In case of ES5.