简体   繁体   English

即使 state 已更新,组件也不会重新渲染

[英]Component is not re-endering even though the state is updated

I am trying to build a simple cart application.我正在尝试构建一个简单的购物车应用程序。

  1. When the item is not in the cart, I am showing Add button -> on clicking add one item will be added to cart, - 1 + will show in the UI.当商品不在购物车中时,我会显示“添加”按钮 -> 单击“添加”时会将一件商品添加到购物车,- 1 + 将显示在 UI 中。
  2. Now when I am clicking on plus(+) button, the store is getting updated, but the change is not getting reflected in UI, it is still showing - 1 + when I go to other tab and come back it is re-rendering so the new state is visible.现在,当我点击加号 (+) 按钮时,商店正在更新,但更改没有反映在 UI 中,它仍然显示 - 1 + 当我 go 到其他选项卡并返回时它正在重新渲染所以新的 state 可见。
  3. Now say I have - 10 +, when I will click - 5 times, then it will be removed from the cart as 0 items are there, this state is visible, but intermediate change when the only count of the item is changing is not rendering the UI.现在说我有 - 10 +,当我点击 - 5 次时,它会从购物车中删除,因为那里有 0 件商品,这个 state 是可见的,但是当商品的唯一计数发生变化时,中间变化不会呈现用户界面。

My Selector code.我的选择器代码。

const cartItem: CartItem = useSelector((state) => {
    if (
      !state ||
      !state.cart ||
      !state.cart.items ||
      state.cart.items.length === 0
    ) {
      return {quantity: 0};
    }
    const result = state.cart.items.find(
      (item: CartItem) => item.itemId === inventory.id,
    );
    console.log('result = ' + JSON.stringify(result));
    return result;
  });

Complete component code.完整的组件代码。

function InventoryView({inventory, navigation}: IProps) {
  const cartItem: CartItem = useSelector((state) => {
    if (
      !state ||
      !state.cart ||
      !state.cart.items ||
      state.cart.items.length === 0
    ) {
      return {quantity: 0};
    }
    const result = state.cart.items.find(
      (item: CartItem) => item.itemId === inventory.id,
    );
    console.log(JSON.stringify('result = ' + JSON.stringify(result)));
    return result;
  });

  console.log('cart item =' + JSON.stringify(cartItem));
  const shouldShowAddButton = !cartItem || !cartItem.quantity;
  console.log('shouldShowAddButton' + shouldShowAddButton);
  const dispatch = useDispatch();
  return (
    <View style={[styles.cardView]}>
      <View>
        <Text style={styles.textMain}>{inventory.name}</Text>
        <View style={styles.costRow}>
          <Text style={styles.costText}>₹ {inventory.price}</Text>
          <Text style={styles.costUnitText}> {inventory.unit}</Text>
        </View>
      </View>
      {shouldShowAddButton && (
        <TouchableOpacity
          style={styles.addButton}
          onPress={() =>
            dispatch(
              addToCart({
                itemId: inventory.id,
                quantity: 1,
                price: inventory.price,
                name: inventory.name,
              }),
            )
          }>
          <Text style={styles.addText}>Add</Text>
        </TouchableOpacity>
      )}
      {!shouldShowAddButton && (
        <View style={{alignItems: 'flex-end'}}>
          <View style={{flexDirection: 'row', alignItems: 'center'}}>
            <TouchableOpacity
              style={styles.buttonMinus}
              onPress={() => dispatch(decreaseQuantity(inventory.id))}>
              <Text>-</Text>
            </TouchableOpacity>
            <Text style={styles.addText}>{cartItem.quantity}</Text>
            <TouchableOpacity
              style={[styles.buttonMinus, styles.buttonPlus]}
              onPress={() => dispatch(increaseQuantity(inventory.id))}>
              <Text>+</Text>
            </TouchableOpacity>
          </View>
          <TouchableOpacity
            style={[styles.deleteButton]}
            onPress={() => dispatch(removeFromCart(inventory.id))}>
            <Text style={styles.deleteButtonTextStyle}>Remove</Text>
            {/* <Image source={require('../assets/pngs/delete.png')} /> */}
          </TouchableOpacity>
        </View>
      )}
    </View>
  );
}

My Reducer Code我的减速器代码

import {CartItem} from '../models/CartItem';

export const ADD_TO_CART = 'ADD_TO_CART';
export const REMOVE_FROM_CART = 'REMOVE_FROM_CART';
export const INCREASE_QUANTITY = 'INCREASE_QUANTITY';
export const DECREASE_QUANTITY = 'DECREASE_QUANTITY';

export interface CartReducerState {
  items: CartItem[];
}
export const cartInitialSate: CartReducerState = {
  items: [],
};

const cartReducer = (state = cartInitialSate, action: any) => {
  switch (action.type) {
    case ADD_TO_CART:
      console.log(JSON.stringify(action.data));
      const updatedState = {
        ...state,
        items: [...state.items, action.data],
      };
      console.log(JSON.stringify(updatedState));
      return updatedState;
    case REMOVE_FROM_CART:
      return {
        ...state,
        items: state.items.filter((item) => item.itemId !== action.data.id),
      };
    case INCREASE_QUANTITY:
      return {
        ...state,
        items: state.items.map((item) => {
          if (item.itemId === action.data.id) {
            item.quantity++;
          }
          return item;
        }),
      };
    case DECREASE_QUANTITY:
      return {
        ...state,
        items: state.items
          .map((item) => {
            if (item.itemId === action.data.id) {
              item.quantity--;
            }
            return item;
          })
          .filter((item) => item.quantity && item.quantity > 0),
      };
    default:
      return state;
  }
};
export {cartReducer};

UI will look like this用户界面看起来像这样在此处输入图像描述

In the INCREASE_QUANTITY of Cart Reducer.在 Cart Reducer 的 INCREASE_QUANTITY 中。 Instead of returning the same object try returning a new one.不要返回相同的 object,而是尝试返回一个新的。

case INCREASE_QUANTITY:
  return {
    ...state,
    items: state.items.map((item) => {
      if (item.itemId === action.data.id) {
        item.quantity++;
        return {...item};
      }
      return item;
    }),
  };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 即使使用钩子更新了父状态,子组件也不会重新渲染 - Child component not re-rendering even though parent state is updated using hooks 为什么即使使用钩子更新父 state 也不重新渲染子组件 - Why isn't child component re-rendered even though parent state is updated using hooks 我不知道为什么我的组件不呈现更新状态。 即使状态被更新并反映在数据库中 - I can't figure out why my component does not rendered with the updated state. Even though, the state is updated and reflected in the database 即使调用render函数中的console.log,组件也不会在状态改变时重新渲染 - Component won't re-render on state change, even though console.log in render function is called localStorage 保存未更新的状态,即使它出现在 setState 之后 - localStorage saving non updated state even though it comes after setState 即使商店已更新,Redux也不会​​重新渲染React组件 - Redux not Re-rendering React components even though store is updated 尽管状态已更新,但不会重新渲染子组件 - Component Child is not re-rendered although state updated 反应子组件不会在更新的父状态上重新渲染 - React child component not re-rendering on updated parent state 更新 state 时反应 @redux/toolkit 不重新渲染组件 - React @redux/toolkit not re-rendering component when state is updated 即使商店状态发生了变化,UI是否也没有重新显示? - UI is not re-rendring even though the store state is changing?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM