this.state.search_results.map不是一个函数,但它是一个数组

时间:2016-03-21 21:40:23

标签: javascript arrays reactjs javascript-objects

render: function(){
console.log(this.state.search_results);
var renderedSearchResults = this.state.search_results.map((result) => {

console.log打印:

  

[{" id":" testGroup2"},{" id":" testGroup77777"},{" id& #34;:" testGroup1"},{" id":" testGroup3"}]

数据通过以下方式获得:

$.ajax({
        url: this.props.routes.search,
        contentType: 'application/json',
        type: 'POST',
        data: JSON.stringify(searchObj),
        success: function(data){
            console.log(data);
            this.setState({search_results:data});
        }.bind(this),
        error: function(xhr, status,err){
            console.error("/api/response", status, err.toString());
        }.bind(this)
        });```

通过:

def post(self):
    """
    Makes a request to search for a specific
    searchtype: Group
    searchstring: ""
    requestedfields: []
    """
    search_type = self.json_data.get('searchtype', 'Group')
    search_string = self.json_data.get('searchstring', '')
    requestedfields = self.json_data.get('requestedfields', ['id'])
    search_model = {
        'Group': Group(),
        'User': User()
    }[search_type]
    search_fields = {
        'Group': ['id', 'tags'],
        'User': ['username']
    }[search_type]
    # check if requestedfields contains valid fields
    for field in requestedfields:
        if field == 'id':
            continue
        value = search_model.default().get(field, None)
        if value is None:
            return self.set_status(400, "Model {0} does not have requested field {1}".format(search_type, field))
    try:
        search_results = search_model.search_items(search_string, search_fields, requestedfields)
    except err:
        return self.set_status(400, "Something went wrong")
    self.set_status(200, "Success")
    return self.write(tornado.escape.json_encode(search_results))

我真的很困惑this.state.search_results不是一个我可以迭代的阵列,任何人都可以看到发生了什么?

我已尝试在成功功能中使用console.log(Object.prototype.toString.call(data));,我得到:

[object String]

2 个答案:

答案 0 :(得分:1)

尝试以明确的方式设置json数据类型,同时执行ajax请求:

$.ajax({
  dataType: 'json',
  //...
});

用于通过jQuery检测数据类型的Intelligent Guess很可能是错误的结果。

答案 1 :(得分:0)

找到我的答案,没有设置dataType:" json"在我的ajax请求中。