想从外部JSON文件呈现API,但出现错误
问题描述:
我正在使用本地.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。
答
您的组件
import $ from 'jquery' //In case of ES 6
var $ = require('jquery'); //In case of ES5.
使用NPM这样
进口的jQuery您必须手动输入的jQuery中安装jQuery。你可以使用'fetch()'这是默认方法来使api请求 –
'{this.state.tree}'会产生错误,因为反应无法打印对象。尝试'{JSON.stringyfy(this.state.tree)}' –
我个人更喜欢'axios'来在反应环境中做请求。 JQuery适用于dom操作和其他许多事情,但在使用React等UI框架时并不是必须的 – Icepickle