动作可能没有未定义的“type”属性。你是否拼错了一个常量? (反应 JS)

问题描述 投票:0回答:1

使用 redux 从 django 调用 api。 Django 服务器正在运行。我们做商店就像:

import { applyMiddleware, combineReducers, createStore } from "redux";
import { composeWithDevTools } from "redux-devtools-extension";
import thunk from "redux-thunk";
import { productListReducer } from "./reducers/productReducers";


const reducer = combineReducers({
  productList: productListReducer,
});

const initialState = {};

const middleware = [thunk];

const store = createStore(
  reducer,
  initialState,
  composeWithDevTools(applyMiddleware(...middleware))
);

export default store;

我的产品减速器是:

import {
  PRODUCT_LIST_FAIL,
  PRODUCT_LIST_REQUEST,
  PRODUCT_LIST_SUCCESS,
} from "../constants/productConstants";

export const productListReducer = (state = { products: [] }, action) => {
  switch (action.type) {
    case PRODUCT_LIST_REQUEST:
      return { loading: true, products: [] };
    case PRODUCT_LIST_SUCCESS:
      return { loading: false, products: action.payload };
    case PRODUCT_LIST_FAIL:
      return { loading: false, error: action.payload };
    default:
      return state;
  }
};

产品行动:

import axios from "axios";
import {
  PRODUCT_LIST_FAIL,
  PRODUCT_LIST_REQUEST,
  PRODUCT_LIST_SUCCESS,
} from "../constants/productConstants";

export const listProducts = () => async (dispatch) => {
  try {
    dispatch({ type: PRODUCT_LIST_REQUEST });
    const { data } = await axios.get("/api/products/");
    console.log("Loading..")
    console.log(data)

    dispatch({
      type: PRODUCT_LIST_SUCCESS,
      payload: data
    });
  } catch (error) {
    dispatch({
      type: PRODUCT_LIST_FAIL,
      payload:
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message,
    });
  }
};

HomeScreen.js

import { useDispatch } from 'react-redux'
import { listProducts } from "../actions/productActions";

const dispatch = useDispatch()
useEffect(() => {
    dispatch(listProducts())
    


  }, [dispatch]);

当我们使用 useEffect 调用 api 时,我们没有获取 api 数据。我们得到空数据并且还得到 错误:操作可能没有未定义的“类型”属性。您是否拼错了一个常量。请帮我解决这个问题。

在这里我给你一些照片,

enter image description here

enter image description here

reactjs redux react-redux redux-thunk redux-toolkit
1个回答
0
投票

这个

dispatch(listProducts())
需要是
listProducts(dispatch)
,因为listProducts有调用调度。

© www.soinside.com 2019 - 2024. All rights reserved.