首先我必须说我来自移动开发。我对网络开发非常陌生,所以这可能是一个业余问题。
我正在使用 create-react-app (使用 Babel)构建一个react.js 项目。我正在尝试遵循一个教程,在该教程中我应该在安装组件时导入 *.json 文件。我似乎无法访问我的数据,并且收到一条错误消息“filteredApts.map 不是函数”。
这是我的导入:
import React from 'react';
import './App.css';
import $ from 'jquery';
这是我的 componentWillMount 方法:
componentDidMount: function() {
console.log($.get('./data.json', function(){}.bind(this))) //This seems to get an HTML Page returned!
this.serverRequest = $.get('./data.json', function(result) {
var tempApts = result;
this.setState({
myAppointments: tempApts
}); //setState
}.bind(this));
},
我的渲染方法:
render: function() {
var filteredApts = this.state.myAppointments;
filteredApts = filteredApts.map(function(item, index) {
return (<li className="pet-item media" key={index}>
<div className="pet-info media-body">
<div className="pet-head">
<span className="pet-name">{this.state.myAppointments[index].petName}</span>
<span className="apt-date pull right">{this.state.myAppointments[index].petName}</span>
</div>
<div className="owner-name"><span className="label-item">Owner:</span>
{this.state.myAppointments[index].ownerName}</div>
<div className="apt-notes">
{this.state.myAppointments[index].aptNotes}</div>
</div>
</li>)
}.bind(this));
return (<div className="interface">
<div className="item-list media-list">
<ul className="item-list media-list"></ul>
</div>
</div>)
} //render
}); //MainInterface
这是我的文件 map :
最后是我的控制台日志:
有人能够指出我可能做错了什么吗?
最佳答案
我建议更改此行:
var filteredApts = this.state.myAppointments;
到此
var filteredApts = this.state.myAppointments || [];
您使用异步数据获取,并且在渲染时它还不能是 myAppointments。
关于javascript - 无法使用 jQuery 和 React.js 加载 data.json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40166937/