【问题标题】:Cannot read property 'sort' of undefined in reactjs无法读取 reactjs 中未定义的属性“排序”
【发布时间】:2019-01-05 13:19:29
【问题描述】:

当我从 API 获取数据并且想要对数据进行排序和显示时,我收到以下错误 TypeError: Cannot read property 'sort' of undefined,我的排序函数适用于本地静态数据,但不适用于端点。

下面是排序功能

dynamicSort(property) {
        var sortOrder = 1;
        if(property[0] === "-") {
            sortOrder = -1;
            property = property.substr(1);
        }
        return function (a,b) {
            if(sortOrder == -1){
                return b[property].localeCompare(a[property]);
            }else{
                return a[property].localeCompare(b[property]);
            }        
        }
    }

下面是我的渲染方法

render() {
let data = this.props.brands.all_brands
data.sort(this.dynamicSort("name"));
console.log(data);
}

以下是我的 JSON 格式

{
"all_items": [
{"name": "Banana"},
{"name": "Cat"},
{"name": "Apple"}
]
}

【问题讨论】:

  • 你能分享你传递给组件的道具吗? this.props.brands 似乎不包含 all_brands 属性

标签: javascript json reactjs sorting ecmascript-6


【解决方案1】:

JS 尝试在此时为 undefined 的变量调用 sort() 方法。我猜你的道具此时没有通过。如果您确定随时将它们传递给组件,则只需添加一个 if 检查:

render() {
  let data = this.props.brands.all_brands
  if (data) data.sort(this.dynamicSort("name"));
  console.log(data);
  // return your template
}

【讨论】:

    【解决方案2】:

    远程数据是异步的,这意味着获取它需要时间,所以你需要处理你还没有得到它的情况:

    all_brands 未定义,直到获取远程数据:

    render() {
        let data = this.props.brands.all_brands
    
        if (data) {
            data.sort(this.dynamicSort("name"));
            console.log(data);
        } else {
            return 'loading...'    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-16
      • 2020-04-23
      • 2016-08-08
      • 2018-12-16
      • 1970-01-01
      • 2021-08-26
      • 2021-12-06
      • 2021-12-06
      相关资源
      最近更新 更多