React:使用Ajax调用第三方API(Behance)

时间:2017-04-03 23:44:04

标签: jquery reactjs

我正在尝试使用Behance API根据我的搜索栏中输入的关键字来获取列表项目,但是..在我的搜索栏上提交输入后,我一直收到此错误:

BeSearchContainer.js:35 Uncaught TypeError: Cannot read property 'done' of undefined

我的onSubmit功能:

 // triggered whenever the user submits the Search form
    onSubmitQuery(e) {
     e.preventDefault()
     let component = this
 // my error is from this next line..
      queryBehance(this.state.query).done( data => { 
       component.setState({
       query: '',
       hasSearched: !component.state.hasSearched,
       projects: data,
     })
   })
  }

我的$ .ajax功能:

import $ from 'jquery'

 export function queryBehance(query) {
 var term = query.replace(/\s/, "+"); 
 var url = "https://www.behance.net/v2/projects?
 client_id={client_id}&field=" + term;

    return
    $.ajax({
      url: url,
      type: "get",
      data: {projects: {}},
      dataType: "jsonp",
    }).done((response) => {
      console.log(response);
      return response["projects"]
    }).fail(() => {
      console.log("Ajax request fails")
    })
   };

我需要调整我的Ajax方法,还是我onSubmitQuery函数的语法错误?请原谅我缺乏知识,因为我是React的新手:)任何建议都会非常感激!

1 个答案:

答案 0 :(得分:0)

如果您的代码完全按照问题中的方式编写,则[ { "id" : "001", "name" : "Ram", "age" : 53, "Designation" : "Manager", "Location" : "Hyderabad" }, { "id" : "002", "name" : "Robert", "age" : 43, "Designation" : "SR.Programmer", "Location" : "Chennai" }, { "id" : "003", "name" : "Rahim", "age" : 25, "Designation" : "JR.Programmer", "Location" : "Delhi" } ] 功能在queryBehance关键字之后会遇到automatic semicolon insertion。将return移至与$.ajax相同的行:

return