【问题标题】:Why my shallow comparison in React.memo() is not working?为什么我在 React.memo() 中的浅层比较不起作用?
【发布时间】:2021-09-13 07:54:28
【问题描述】:

嘿,我正在制作一个送餐应用。我目前正在实现购物车功能。 我一直在记忆我自己构建的自定义增量器。我正在使用 Flatlist 来呈现数据:

这是我的 CartRowRender 代码:

import React, { useState, memo, useRef, useCallback } from "react";
import { StyleSheet, Text, View, Dimensions } from "react-native";

import CartIncrementor from "./CartIncrementor";
import Incrementor from "./Incrementor";


const CartRowRender = ({ item }) => {

  return (
    <>
      <View style={styles.card}>
        <View style={styles.cardItems}>
          <Text style={styles.text}>
            {item.name}
          </Text>
          <CartIncrementor
            value={item.quantity}
            id={item.id}
            subDataId={item.subDataId}
            price={item.price}
          />
          <View style={styles.priceView}>
            <Text style={styles.text}>₹ {item.quantityPrice}</Text>
          </View>
        </View>
      </View>
    </>
  );
};

function checkEqualProps(prevProps, nextProps) {
  console.log(prevProps, nextProps);
  console.log(
    "Equal quantity Price",
    prevProps.quantityPrice == nextProps.quantityPrice,
    "Equal quantity",
    prevProps.quantity == nextProps.quantity
  );
   return prevProps.quantityPrice === nextProps.quantityPrice;
}
export default memo(CartRowRender, checkEqualProps);

由于某些原因,浅比较似乎不起作用。当我控制台注销功能 checkEqualProps 时,它显示上一个数量和下一个数量相等。

【问题讨论】:

    标签: reactjs react-native react-hooks


    【解决方案1】:

    您打印出两件事,但只使用一件事作为返回值。你可能是说

    return (
      prevProps.quantityPrice === nextProps.quantityPrice &&
      prevProps.quantity === nextProps.quantity
    );
    

    ?

    【讨论】:

    • 我认为这行得通,但问题是项目的总价格发生了变化,但增量值及其价格保持不变。
    猜你喜欢
    • 2020-09-14
    • 2015-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-05
    • 1970-01-01
    • 2018-05-11
    相关资源
    最近更新 更多