Created
April 9, 2024 03:54
-
-
Save hevi1991/83fbeda44f293f89b188ff8886346f81 to your computer and use it in GitHub Desktop.
React useReducer 示例
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React, { useReducer } from "react"; | |
| import ReactDOM from "react-dom"; | |
| const initialState = { | |
| items: [], | |
| total: 0 | |
| }; | |
| const actions = { | |
| ADD_ITEM: "ADD_ITEM", | |
| REMOVE_ITEM: "REMOVE_ITEM" | |
| }; | |
| const reducer = (state, action) => { | |
| switch (action.type) { | |
| case actions.ADD_ITEM: | |
| return { | |
| items: [...state.items, action.payload], | |
| total: state.total + action.payload.price | |
| }; | |
| case actions.REMOVE_ITEM: | |
| const updatedItems = state.items.filter(item => item.id !== action.payload.id); | |
| const updatedTotal = state.total - action.payload.price; | |
| return { | |
| items: updatedItems, | |
| total: updatedTotal | |
| }; | |
| default: | |
| return state; | |
| } | |
| }; | |
| function ShoppingCart() { | |
| const [state, dispatch] = useReducer(reducer, initialState); | |
| const addItemToCart = (item) => { | |
| dispatch({ type: actions.ADD_ITEM, payload: item }); | |
| }; | |
| const removeItemFromCart = (item) => { | |
| dispatch({ type: actions.REMOVE_ITEM, payload: item }); | |
| }; | |
| return ( | |
| <div> | |
| <h1>Shopping Cart</h1> | |
| <ul> | |
| {state.items.map(item => ( | |
| <li key={item.id}> | |
| {item.name} - ${item.price} | |
| <button onClick={() => removeItemFromCart(item)}>Remove</button> | |
| </li> | |
| ))} | |
| </ul> | |
| <p>Total: ${state.total}</p> | |
| <button onClick={() => addItemToCart({ id: 1, name: "Product 1", price: 10 })}>Add Product 1</button> | |
| <button onClick={() => addItemToCart({ id: 2, name: "Product 2", price: 20 })}>Add Product 2</button> | |
| </div> | |
| ); | |
| } | |
| const rootElement = document.getElementById("root"); | |
| ReactDOM.render(<ShoppingCart />, rootElement); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment