无法使用Redux从Axios获取数据

iqjalb3h  于 2023-03-02  发布在  iOS
关注(0)|答案(1)|浏览(150)

我试图使用axios向我的eccomerce api发出axios请求,但它返回空,我尝试了很多东西,但它不工作,这些是我的文件:
store.js(我尝试使用configureStore,但它得到错误):

const reducer = combineReducers({
    products: productsReducer
})

let initialState = {}

const middlware = [thunk];
const store = createStore(reducer, initialState, composeWithDevTools(applyMiddleware(...middlware)))

export default store;

产品减速器:

import { 
    ALL_PRODUCTS_FAIL,
    ALL_PRODUCTS_REQUEST,
    ALL_PRODUCTS_SUCCESS,
    CLEAR_ERRORS} from '../constants/productConstants';
export const productsReducer = (state = { products:[] }, action) => {
    switch(action.type){
        case ALL_PRODUCTS_REQUEST:
            return {
                loading: true,
                products: []
            }
        case ALL_PRODUCTS_SUCCESS:
                return {
                    loading: false,
                    products: action.payload.products,
                    productsCount: action.payload.productsCount,
            }
        case ALL_PRODUCTS_FAIL:
                return {
                    loading: false,
                    error: action.payload
            }
            case CLEAR_ERRORS:
                return {
                    ...state,
                    error: null
            }
         
        default:
            return state;
    }
}

变量:

export const ALL_PRODUCTS_REQUEST = 'ALL_PRODUCTS_REQUEST'
export const ALL_PRODUCTS_SUCCESS = 'ALL_PRODUCTS_SUCCESS'
export const ALL_PRODUCTS_FAIL = 'ALL_PRODUCTS_FAIL'
export const CLEAR_ERRORS = 'CLEAR_ERRORS'

actions. js(我检查过网址没问题,网址的其余部分在package.json中):

export const getProducts = () => async(dispatch) => {
    try {
        dispatch({type: ALL_PRODUCTS_REQUEST})
        const { data } = await axios.get('/api/products')
        dispatch({
            type: ALL_PRODUCTS_SUCCESS,
            payload: data
        })
    } catch (error) {
        dispatch({
            type: ALL_PRODUCTS_FAIL,
            payload: error.response.data.message
        })
    }
}

// Clear Errors
export const clearErrors = () => async (dispatch) => {
    dispatch({
        type: CLEAR_ERRORS
    })
}

和home.js,它不会在redux devtools中返回任何内容,因此我无法获取数据

const dispatch = useDispatch();

    useEffect(() => {
       dispatch(getProducts)
    }, [dispatch])
w6mmgewl

w6mmgewl1#

看起来您缺少用于调用useEffect钩子中getProducts函数的圆括号。您可以尝试将dispatch(getProducts)更改为dispatch(getProducts())。
此外,请确保您已经在Home组件中正确导入了getProducts操作函数。
包含所述变更的代码:

import React, { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { getProducts } from '../actions/productActions';

const Home = () => {
  const dispatch = useDispatch();

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

  return <h1>Home</h1>;
};

export default Home;

确保API端点/api/products返回预期的数据。您还可以在操作中添加一些控制台日志,以检查是否正在发出API请求以及响应数据是否存储在Redux存储中。

import { 
  ALL_PRODUCTS_FAIL,
  ALL_PRODUCTS_REQUEST,
  ALL_PRODUCTS_SUCCESS,
  CLEAR_ERRORS
} from '../constants/productConstants';
import axios from 'axios';

export const getProducts = () => async(dispatch) => {
  try {
    dispatch({type: ALL_PRODUCTS_REQUEST});
    const { data } = await axios.get('/api/products');
    console.log(data); // check the response data
    dispatch({
      type: ALL_PRODUCTS_SUCCESS,
      payload: data,
    });
  } catch (error) {
    dispatch({
      type: ALL_PRODUCTS_FAIL,
      payload: error.response.data.message,
    });
  }
};

// Clear Errors

export const clearErrors = () => async (dispatch) => {
  dispatch({
    type: CLEAR_ERRORS,
  });
};

相关问题