【问题标题】:Filtering out data React Native best practice过滤掉数据 React Native 最佳实践
【发布时间】:2020-08-01 07:30:41
【问题描述】:

我需要有关在何处执行数据过滤以实现最佳性能的建议。假设我从远程 API 的一个端点接收大量 产品,从另一个端点接收 产品类别。我将它们存储在Redux 状态,并且还保存到Realm 数据库,以便它们可以离线使用。

在我的应用程序中,我有一个包含 2 个屏幕的 Stack.NavigatorProductCategoriesProductsList。当您按下一个类别时,它会将您带到屏幕上,其中包含属于该类别产品。目前,我在我的组件内部执行数据过滤,据我了解,每次渲染组件时它都会触发,我怀疑这种方法会减慢应用程序的速度。 所以我想知道是否有更好的方法来做到这一点?也许在应用加载时提前过滤每个category的数据?

我的代码如下:

const ProductCategories = (props) => {

const isFocused = useIsFocused();

useEffect(() => {
    if (isFocused) {
      setItems(props.productCategories);
    } 
  }, [isFocused]);

return ( 
 ...
 );
};

const mapStateToProps = (state) => ({
  productCategories: state.catalog.productCategories,
});
const ProductsList = (props) => {

const isFocused = useIsFocused();

const productsFilteredByCategory = props.products.filter((product) => {
    return product.category === id;
  });
  useEffect(() => {
    if (isFocused) {
      setItems(productsFilteredByCategory);
    } 
  }, [isFocused]);

return (
...
)


const mapStateToProps = (state) => ({
  products: state.catalog.products,
});


【问题讨论】:

    标签: arrays reactjs react-native react-redux react-navigation


    【解决方案1】:

    你必须对redux中的数据进行归一化(可以看到主要原理here),到下一个视图:

    // redux store
    {
      categories: {
        1: { // id of category
          id: 1,
          title: 'some',
          products: [1, 2, 3] // ids of products
        },
        ...
      },
      products: {
        1: { // id of product
          id: 1,
          title: 'some product',
        },
        ...
      }
    }
    

    然后您可以创建一些选择器,即使没有记忆,它们的工作也比过滤器快得多,因为按属性从对象中获取数据的时间是恒定的

    const getCategory = (state, categoryId) => state.categories[categoryId]
    const getProduct = (state, productId) => state.products[productId]
    
    const getCategoryProducts = (state, categoryId) => {
      const category = getCategory(state, categoryId);
    
      if (!category) return [];
    
      return category.products.map((productId) => getProduct(state, productId))
    }
    

    【讨论】:

      猜你喜欢
      • 2013-02-04
      • 2014-08-01
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 2014-05-23
      • 2015-11-16
      • 1970-01-01
      • 2016-07-25
      相关资源
      最近更新 更多