简体   繁体   中英

Updating Redux state issue?

This is a piece of the code:

  const cart = useSelector((state) => state.cart);
  // const [totalSum, setTotalSum] = useState(0.0);

  // const dispatch = useDispatch();

  const updateSum = () => {
    var newSum = 0;
    var i;
    for (i = 0; i < productsInCart.length; i++) {
      newSum = newSum + productsInCart[i].prod.price * productsInCart[i].count;
    }
    // setTotalSum(newSum);
    cart.totalAmount = newSum;
    // dispatch(setTotal(newSum));
  };

Some of the lines are commented out, so let me explain:

  1. I have a redux set up. Here I'm manually updating the redux state cart.totalAmount = newSum . But it doesn't display the update until I manually save my code file with Ctrl + S .

  2. However, if I do keep and uncomment the useState() parts( // const [totalSum, setTotalSum] = useState(0.0); // setTotalSum(newSum); )which is commented out right now, it works perfectly fine. The problem is I am not using the useState() anywhere else, it kinda left there from previous stages of coding.

  3. So trying a different way I removed useState() completely and tried dispatching the reducer method to update the state // const dispatch = useDispatch(); // dispatch(setTotal(newSum)); // const dispatch = useDispatch(); // dispatch(setTotal(newSum)); Now the app crashing when I go to that screen.

THIS IS THE REDUCER CODE JUST IN CASE:

import { ADD_TO_CART, CLEAR_CART, SET_TOTAL } from "../actions/cart";
import ProductInCart from "../../models/ProductInCart";

const initState = {
  productsInCart: [],
  totalAmount: 0,
};

const cartReducer = (state = initState, action) => {
  switch (action.type) {
    case ADD_TO_CART:
      return {
        productsInCart: state.productsInCart.concat(
          new ProductInCart(
            Math.random().toString(),
            action.product,
            action.num
          )
        ),
        totalAmount: state.totalAmount,
      };
    case CLEAR_CART:
      const newCart = [];
      return {
        ...state,
        productsInCart: newCart,
        totalAmount: 0,
      };
    case SET_TOTAL:
      return { ...state, totalAmount: action.totalAmount };
    default:
      return state;
  }
};

export default cartReducer;

I understand I'm not getting the idea with the states, how they work and updating them. Can't see what it is.THANKS IN ADVANCE.

I dont know what you are trying to achieve with this piece of code.

dispatch(setTotal(newSum));

For Redux to work you need to have Action, Reducer and Middleware if you are using one. More on this matter can be found here .

In your case I'll use Action and Reducer.

First we need a Reducer which stores previous state and returns new state if updated. Let's say we are updating Total Amount. Then our Reducer will be.

case TOTAL_AMOUNT:
return {...state,TotalAmount:action.payload}

action.payload will contain the values that will update your previous value in TotalAmount. Now, where will we get this payload from? We will get it from Action.

Our action will look like.

export const UpdateTotalAmount = (data) => ({type:TOTAL_AMOUNT,payload:data})

Remember we needed to pass payload to Reducer? This is where we are sending that payload. So, this action is receiving data from our UI and passing that data to the reducer.

Now, how do we receive this data from UI? It actually is one line code. In our UI dispatch action and pass the value.

dispatch(UpdateTotalAmount(newSum));

Now everytime we call updateSum function and send new value our state in reducer will get updated.

you can use the state in any React Components using useSelector.

const desiredName = useSelector((state)=>state.cartReducer.TotalAmount)

Also dont forget to add cartReducer to Root Reducer. More here . Hope you understood. Sorry for bad English.

You can try by connecting the component with store using connect ("which is a method of react-redux library") It takes two methods as an argument one of them is mapDispatchToProps which will provide you the dispatch method in your functional component. Try using that instead of using dispatch hook or preferably you can make a POC on https://codesandbox.io/s/react-redux-template-forked-dbw6n?file=/src/App.js:450-463 so we can have a better understanding of your problem Thanks

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