【问题标题】:Cannot load data.json file using jQuery and React.js无法使用 jQuery 和 React.js 加载 data.json 文件
【发布时间】:2016-10-21 01:25:41
【问题描述】:

首先我必须说我来自移动开发。我对网络开发很陌生,所以这可能是一个业余问题。

我正在使用 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

这是我的文件地图:

最后是我的控制台日志:

有人能指出我可能做错了什么吗?

【问题讨论】:

    标签: javascript jquery json reactjs


    【解决方案1】:

    我建议更改此行:

    var filteredApts = this.state.myAppointments;
    

    到这里

    var filteredApts = this.state.myAppointments || [];
    

    您使用异步数据获取,并且在呈现时它可能还没有 myAppointments。

    【讨论】:

      【解决方案2】:

      看起来你的 responseText 是 html。

      【讨论】:

        【解决方案3】:

        我想通了。

        首先,'./data.json' 默认指向公用文件夹。

        其次,我在

        中缺少 {filteredApts}
        return (<div className="interface">
                       <ul className="item-list media-list">{filteredApts}</ul>
                    </div>)
        

        谢谢大家。

        【讨论】:

          猜你喜欢
          • 2015-05-13
          • 1970-01-01
          • 2021-02-17
          • 2015-06-26
          • 2017-06-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-04-03
          相关资源
          最近更新 更多