简体   繁体   中英

react: how to get data from redux store in a rendered component?

In my redux store, I have products and cartItems. when I render every single product I also give a button called addToCart on every product. so when I clicked the button, that item is added on the cartItems array (store)

now every cart item has a quantity property. so that if add to cart button is called again, I increment the quantity.

what I want is the value of the quantity of that cartItem in my rendered product component. so that I can conditionally give the add to cart button's text content like that:

${cartItem.quantity} on bag

this is my product component:

const Product = ({
  id,
  title,
  brand,
  price,
  image_url,
  addCartItem
}) => {
  const [isClicked, setIsClicked] = useState(false);

  const handleAddToCart = (id) => {
    setIsClicked(true);
    addCartItem(id);
  };


  return (
    <div className='product'>
      {/* <Link to={`/product/${id}`}> */}
      <img src={image_url} alt={title} />
      <div className='title'>
        <span>{title}</span>
        <span>{brand}</span>
      </div>
      {/* </Link> */}
      <div className='actions'>
        <span>${price}</span>
        <button onClick={() => handleAddToCart(id)}>
          {isClicked ? `${I need quantity here} in Bag` : 'Add to Cart'}
        </button>
      </div>
    </div>
  );
};

You said you have a reducer named cartItems[] and in which you store product{} after user clicks add to cart button. Okay, simple logic. Now what you want is a property named quantity that is in every product of cartItems[] . You can get that property using redux's useSelector hook(since you're using hooks).

const { quantity } = useSelector(store => store.cartItems.find(item => item.id === id));

What we are doing here is that we are getting the target product from the cartItems array using the id that's getting passed in as argument and then accessing the quantity from that product. This will be very bad for performance if the products[] list is large and the cartItems[] is large as well. Try to use an object to store the cartItems{} and access it like

const quantity = useSelector(store => store.cartItems[id].quantity);

This approach is very performant since there's no loop, it's O(1).

Hope this answers your question.

I hope you connected properly the reducer to the global store using combinereducer, if you connected then you can use like this - import the useSelector from the react-redux, since you are using react hooks,

import { useSelector} from 'react-redux';

and simply call useSelector inside the function like this to get the data

  const taskDetails = useSelector((state) => (state.taskDetails.entities));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM