redux 如何在React Router v6中推到历史记录?我面临未找到消息

uujelgoq  于 2022-11-12  发布在  React
关注(0)|答案(1)|浏览(152)

我使用了react@18reduxreact-router@6。我的产品页面上有一个按钮“添加到购物车”,我希望将该产品添加到本地存储中,而我的购物车页面上有该产品。单击“添加到购物车”按钮后,我转到了ID为的购物车页面,但它显示未找到。如何解决此问题?
应用程序. js:

<BrowserRouter>
  <Routes>
    <Route path="/" index element={<HomePage />} />
    <Route path="/product/:id" element={<ProductPage />} />
    <Route path="/cart/:id?" element={<CartPage />} />
    <Route path="*" element={<NotFound />} />
  </Routes>
</BrowserRouter>

cartAction.js

export const addToCart = (id) => async (dispatch, getState) => {
  const { data } = await axios.get(http://localhost:8000/products/${id});
  dispatch({
    type: "CART_ADD_ITEM",
    payload: {
      id: data.id,
      title: data.title,
      image1: data.image1,
      price: data.price,
    },
  });
  localStorage.setItem("cartItems", JSON.stringify(getState().cart.cartItems));
};

store.js

const reducer = combineReducers({
  productList: ProductListReducer,
  productDetail: ProductDetailReducer,
  cart: cartReducer,
});

const cartItemsFromLocalStorage = localStorage.getItem("cartItems")
  ? JSON.parse(localStorage.getItem("cartItems"))
  : [];
const initialState = { cart: { cartItems: cartItemsFromLocalStorage } };
const middleWare = [thunk];
const store = createStore(
  reducer,
  initialState,
  applyMiddleware(...middleWare)
);

cartReducer.js

export const cartReducer = (state = { cartItems: [] }, action) => {
  switch (action.type) {
    case "CART_ADD_ITEM":
      const item = action.payload;
      const existingItems = state.cartItems.find(
        (i) => i.id === item.id
      );
      if (existingItems) {
        return {
          ...state,
          cartItems: state.cartItems.map((i) =>
            i.id === existingItems.id ? item : i
          ),
        };
      } else {
        return {
          ...state,
          cartItems: [...state.cartItems, item],
        };
      }

    default:
      return state;
  }
};

购物车页面:

const CartPage = () => {
  const { id } = useParams();
  const dispatch = useDispatch();
  const cart = useSelector((state) => state.cart);
  const { cartItems } = cart;

  console.log(cartItems);

  useEffect(() => {
    if (id) {
      dispatch(addToCart(id));
    }
  }, [dispatch, id]);

  const removeCartHandler= (id) => {
    dispatch(removeCart(id))
  }

  return (
    <Container>
      <Row>
        <Col lg="12">
          <h1>basket</h1>

          {cartItems.length === 0 ? (
            <p className="text-center">there is nothing in the basket</p>
          ) : (
            <ListGroup variant="flush">
              {cartItems.map((item) => {
                return (
                  <ListGroup.Item key={item.id}>
                    <CartItems product={item} remove={()=>removeCartHandler(item.id)}/>
                  </ListGroup.Item>
                );
              })}
            </ListGroup>
          )}
        </Col>
      </Row>
    </Container>
  );
};

购物车项目

const CartItems = ({product}) => {
  return (
    <Row>
      <Col md={2}>
        <Image src={product.image1} alt={product.title} fluid />
      </Col>
      <Col md={3}>{product.title}</Col>
      <Col md={2}>{product.price}</Col>
    </Row>

产品页面

const { id } = useParams();
const navigate = useNavigate();

const addToCartHandler = () => {
  navigate(/cart/${id});
};

<Button className="btn btn-default" onClick={addToCartHandler}>
  <i className="fa fa-shopping-cart"></i> Add to cart
</Button>
qqrboqgw

qqrboqgw1#

从cart路径中删除尾随的"?"react-router-dom@6Route组件不接受可选参数,也不使用path属性中的正则表达式。
path="/cart/:id?"变更为path="/cart/:id"

<BrowserRouter>
  <Routes>
    <Route path="/" element={<HomePage />} />
    <Route path="/product/:id" element={<ProductPage />} />
    <Route path="/cart/:id" element={<CartPage />} />
    <Route path="*" element={<NotFound />} />
  </Routes>
</BrowserRouter>

相关问题