【问题标题】:How can i get a single data from local api using react and redux?如何使用 react 和 redux 从本地 api 获取单个数据?
【发布时间】:2021-12-14 09:08:56
【问题描述】:

我正在尝试创建一个电子商务商店网站,并且我正在使用 redux 来存储我的项目状态,为了在开始时进行简单测试,我在我的后端文件夹中创建了一个本地 api,我已经获取了我的产品数据列表主页成功,但是当我尝试访问单个页面中的单个产品时,它给了我来自 api 状态的 404 错误(未找到产品)!! api 地址绝对正确,我已尝试直接在邮递员中访问该地址并获取数据通过 id 但无法在前端访问该 url...!

这是我的 api 调用操作 >>

      import {
    PRODUCT_DETAILS_START,
    PRODUCT_DETAILS_SUCCESS,
    PRODUCT_DETAILS_FAIL,
  } from "ActionConsts";
  import axios from "axios";


export const getSingleProduct = (productId) => async (dispatch) => {
  dispatch({
    type: PRODUCT_DETAILS_START,
    payload: productId,
  });
  try {
    const { data } = await axios.get(`api/products/${productId}`);
    dispatch({
      type: PRODUCT_DETAILS_SUCCESS,
      payload: data,
    });
  } catch (err) {
    dispatch({
      type: PRODUCT_DETAILS_FAIL,
      payload:
        err.response && err.response.data.message
          ? err.response.data.message
          : err.message,
    });
  }
};

这是我的减速器>>

    export const productDetailReducer = (
      state = { product: {}, loading: true },
      action
    ) => {
      switch (action.type) {
        case PRODUCT_DETAILS_START:
          return { loading: true };
    
        case PRODUCT_DETAILS_SUCCESS:
          return {
            loading: false,
            product: action.payload,
          };
    
        case PRODUCT_DETAILS_FAIL:
          return { loading: false, error: action.payload };
    
        default:
          return state;
      }
    };

这是我的店铺>>

import { createStore, compose, applyMiddleware, combineReducers } from "redux";
import thunk from "redux-thunk";
import { productReducer, productDetailReducer } from "Reducers";

const inState = {};
const reducer = combineReducers({
  productList: productReducer,
  productDetails: productDetailReducer,
});
const composeEnhancers =
  (typeof window !== "undefined" &&
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__) ||
  compose;

const store = createStore(
  reducer,
  inState,
  composeEnhancers(applyMiddleware(thunk))
);

export default store;

这里是门控数据的单页>>

import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { SingelAll } from "Components";
import { useParams } from "react-router-dom";
import { getSingleProduct } from "Actions";

export const Single = (props) => {
  const { id } = useParams();
  const dispatch = useDispatch();
  const productId = id;
  const productDetails = useSelector((state) => state.productDetails);
  const { loading, error, product } = productDetails;

  useEffect(() => {
    dispatch(getSingleProduct(productId));
  }, [dispatch, productId]);

  console.log(product);

  return (
    <>
      <SingelAll loading={loading} error={error} product={product} />
    </>
  );
};

这是未找到的错误>>

我的错误在哪里?

【问题讨论】:

    标签: reactjs api redux react-redux


    【解决方案1】:

    您指定相对于当前页面 url 的 api url:

    ...
    const { data } = await axios.get(`api/products/${productId}`);
    ...
    
    // the api url will change depending on the url of the current page 
    // http://localhost:3000 -> http://localhost:3000/api/products/${productId}
    // http://localhost:3000/product -> http://localhost:3000/product/api/products/${productId}
    // http://localhost:3000/about -> http://localhost:3000/about/api/products/${productId}
    // ...etc
    

    只需为 api 地址添加一个前导斜杠。它确保路径是根目录的绝对路径,而不是当前目录

    ...
    const { data } = await axios.get(`/api/products/${productId}`);
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-27
      • 2019-03-15
      • 2017-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-03
      相关资源
      最近更新 更多