我正在一个电子商务网站上工作,并在其上添加一个 'cart' 路由,但它得到了以下错误:Error image本地主机地址是:3000 / cart,但错误地址来自:3000 / api / products / cart。(我使用 express 从:http:/ / localst:5000 / api / products 获取数据)
此外,如果我输入地址为:“http:/ / localst:3000 / cart / 223”,错误出来为:
GET http://localst:3000/cart/api/products/cart 404 (Not Found)
App.js:
function App() {
return (
<Switch>
<Route exact path="/" component={HomePage} />
<Route exact path="/products" component={ProductPage}/ >
<Route path="/:id" component={ProductDetail} />
<Route path="/cart" component={CartPage} />
<Route path="/cart/:id" component={CartPage} />
</Switch>
)
}
export default App;
cartPage.jsx:
import React, { useEffect } from "react";
import { addToCart } from "../actions/cartActions";
import { useDispatch } from "react-redux";
function CartPage(props) {
const productId = props.match.params.id;
const qty = props.location.search? Number(props.location.search.split("=")[1]): 1;
const dispatch = useDispatch();
useEffect(() => {
if (productId) {
dispatch(addToCart(productId, qty));
}
}, []);
return <div>Hell world!</div>;
}
export default CartPage;
productDetail.jsx:
import React, { useState, useEffect } from "react";
import { useSelector, useDispatch } from "react-redux";
import { detailsProduct } from "../actions/productActions";
function ProductDetail(props) {
const [qty, setQty] = useState(1);
const productDetails = useSelector((state) => state.productDetails);
const { product, loading, error } = productDetails;
const dispatch = useDispatch();
useEffect(() => {
dispatch(detailsProduct(props.match.params.id));
return () => {//};
}, []);
const handleAddToCart = () => {
props.history.push("/cart/" + props.match.params.id + "?qty=" + qty);
};
return ({product.countInStock > 0 && (
<on onClick={handleAddToCart}>
Add to Cart
</on>
)})
http://localst:5000/api/products
:
[
{
name: "Slim Shirt",
category: "Shirts",
image: "/img/d2.png",
price: 60,
brand: "Nike",
rating: 4.5,
numReviews: 10,
_id: "123",
countInStock: 0,
},
{
name: "Best Shirt",
category: "Shirts",
image: "/img/d3.png",
price: 50,
brand: "ads",
rating: 4.6,
numReviews: 12,
_id: "223",
countInStock: 6,
},
....}
server.js:
import express from "express";
import { data } from "./data";
const app = express();
app.get("/api/products/:id", (req, res) => {
const product = data.find((x) => x._id === req.params.id);
if (product) {
res.send(product);
} else {
res.status(404).send({ msg: "Product Not Found!!" });
}
});
app.get("/api/products", (req, res) => {
res.send(data);
});
app.listen(5000, () => {
console.log("server started at http://localst:5000");
});
package.jason:
{
"name": "frontend",
"proxy": "http://127.0.0.1:5000",
"version": "0.1.0",
"private": true,
"dependencies": {
.....}
/ / store.js:
import { createStore, combineReducers, compose,
applyMiddleware } from "redux";
import {
productDetailsReducer,
productListReducer,
} from "./reducers/productReducers";
import thunk from "redux-thunk";
import { cartReducer } from "./reducers/cartReducers";
const initialState = {};
const reduer = combineReducers({
productList: productListReducer,
productDetails: productDetailsReducer,
cart: cartReducer,
});
const composeEnhancer =
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
reduer,
initialState,
composeEnhancer(applyMiddleware(thunk))
);
export default store;
/ / productActions.js:
const listProducts = () => async (dispatch) => {
try {
dispatch({ type: PRODUCT_LIST_REQUEST });
const { data } = await axios.get("api/products");
dispatch({ type: PRODUCT_LIST_SUCCESS, payload: data
});
} catch (error) {
dispatch({ type: PRODUCT_LIST_FAIL, payload:
error.message });
}
};
const detailsProduct = (productId) => async (dispatch) => {
try {
dispatch({ type: PRODUCT_DETAILS_REQUEST, payload:
productId });
const { data } = await axios.get("api/products/" +
productId);
dispatch({ type: PRODUCT_DETAILS_SUCCESS, payload: data
});
} catch (error) {
dispatch({ type: PRODUCT_DETAILS_FAIL, payload:
error.message });
}
};
export { listProducts, detailsProduct };
问题
问题似乎从Switch
组件呈现的路由顺序开始。路由路径顺序和特异性在Switch
中很重要。"/:id"
路由路径小于3特定于,小于特定于
<Switch>
<Route exact path="/" component={HomePage} />
<Route exact path="/products" component={ProductPage} />
<Route path="/:id" component={ProductDetail} /> // matches "/cart"
<Route path="/cart" component={CartPage} /> // unreachable route!!
<Route path="/cart/:id" component={CartPage} /> // unreachable route!!
</Switch>
最后两条路由不可达。当路径为"/cart"
并且发出无效请求时,将呈现错误的组件。
ProductDetail 调度一个操作,该操作可能意味着发出具有正确 ID 的提取请求,bu"cart"
是id
值,其中路径"/cart"
与"/:id"
路由匹配。
useEffect(() => {
dispatch(detailsProduct(props.match.params.id));
return () => {};
}, []);
解决方案
以与路径特定性相反的顺序对路由重新排序。在大多数情况下,这样做也完全消除了使用exact
prop 对所有路由进行胡椒处理的需要。
例子:
<Switch>
<Route path="/cart/:id" component={CartPage} />
<Route path="/cart" component={CartPage} />
<Route path="/products" component={ProductPage} />
<Route path="/:id" component={ProductDetail} />
<Route path="/" component={HomePage} />
</Switch>
请注意,"/cart/:id"
是更特定于"/cart"
、"/products"
和"/:id"
,并且"/cart"
和"/products"
都是更
另请注意,react-router-dom@5
允许Route
组件为path
prop 使用路径数组。请记住,数组中的顺序和特异性仍然很重要。请记住,数组中的所有路由应该比下面 / 后面的路由的路径更具体。
例子:
<Switch>
<Route path={["/cart/:id", "/cart"]} component={CartPage} />
<Route path="/products" component={ProductPage} />
<Route path="/:id" component={ProductDetail} />
<Route path="/" component={HomePage} />
</Switch>
API 请求
对于请求,请尝试使用绝对路径,即axios.get("/api/products/" + productId
),以便请求不是从"/products"
子路由发出的。您希望 API 请求路径类似于"/api/products/123"
而不是"/products/api/products/123"
。
例子:
const listProducts = () => async (dispatch) => {
try {
dispatch({ type: PRODUCT_LIST_REQUEST });
const { data } = await axios.get("/api/products");
dispatch({ type: PRODUCT_LIST_SUCCESS, payload: data });
} catch (error) {
dispatch({ type: PRODUCT_LIST_FAIL, payload: error.message });
}
};
const detailsProduct = (productId) => async (dispatch) => {
try {
dispatch({ type: PRODUCT_DETAILS_REQUEST, payload: productId });
const { data } = await axios.get("/api/products/" + productId);
dispatch({ type: PRODUCT_DETAILS_SUCCESS, payload: data });
} catch (error) {
dispatch({ type: PRODUCT_DETAILS_FAIL, payload: error.message });
}
};
export { listProducts, detailsProduct };
尝试将您的购物车路线移动到您的 /:id 路线上方。
本站系公益性非盈利分享网址,本文来自用户投稿,不代表边看边学立场,如若转载,请注明出处
评论列表(18条)