【问题标题】:React Native Sorting issue反应本机排序问题
【发布时间】:2018-10-24 11:56:40
【问题描述】:

我正在获取一个 JSON 文件并将其存储在两个数组中,并按如下所示的速率对其中一个进行排序,不幸的是,它排序了两个数组 recentPro 和 ratingPro,但要排序的所需数组仅是 ratingPro

fetch(url)
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({
          recentPro: responseJson.products,
          ratedPro:responseJson.products,  
        },
         function() {

           //Sort by rate
           const ratedpro= this.state.ratedPro.sort(function(a, b) {
            return Number(b.rate) - Number(a.rate);
        })
        this.setState({
            ratedPro: ratedpro,     
        })  

        })

平面列表

<FlatList
                data={this.state.ratedPro}
                renderItem={this.mostrated}
                keyExtractor={item => item.pro_name}/>


<FlatList
                data={this.state.recentPro}
                renderItem={this.rederItem}
                keyExtractor={item => item.pro_id} />

【问题讨论】:

    标签: arrays sorting react-native


    【解决方案1】:

    您正在分配 this.state.recentProthis.state.ratedPro 来引用同一个数组。然后,您将更改该数组,这将导致更改同时反映在 this.state.recentProthis.state.ratedPro 中,因为这两个变量都引用了同一个(现在已变异)数组。

    您可以使用slice() 对数组进行浅拷贝,以实现对两个数组的不同排序:

        this.setState({
          recentPro: responseJson.products.slice(),
          ratedPro:responseJson.products.slice(),  
        },
    

    您还通过多次调用setState 触发了不必要和过早的渲染,请考虑以下更简洁的解决方案,该解决方案还对response 进行了一些健全性检查,以防止您的应用程序依赖于您所使用的 API 的响应从以下位置获取数据:

    fetch(url)
      .then(response => response.json())
      .then(responseJson => {
        const { products } = responseJson
    
        if (products && Array.isArray(products)) {  
          const recentPro = products.slice()
    
          const ratedPro = products.slice().sort((a, b) => Number(b.rate) - Number(a.rate))
    
          this.setState({
            recentPro,
            ratedPro,  
          })
        } else { /* display error to user */ }
      }
    

    【讨论】:

      猜你喜欢
      • 2020-03-20
      • 2016-11-10
      • 2019-10-10
      • 1970-01-01
      • 2018-04-03
      • 2017-11-19
      • 2021-03-15
      • 1970-01-01
      相关资源
      最近更新 更多