为什么 axios.get 在我使用 redux 时不起作用?

Why axios.get doesn't work when I use redux?

我正在用 json 文件中的图片创建一个页面。在我添加 redux 之前它一直有效。我是 redus 的新手所以我希望你能帮助我找到我的错误。谢谢。

import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { getCards } from "../cardsActions";
import PortfolioItem from "../Pages/PortfolioItem";

export default function Portfolio() {

  const dispatch = useDispatch();
  const cardsListData = useSelector((state) => state.cardsList);
  const { loading, error, cards } = cardsListData;
  useEffect(() => {
    dispatch(getCards());
  }, [dispatch]);

  return (
    <div className="container">
      <div className="portfolio-wrapper">
        {loading
          ? "Loading..."
          : error
          ? error.message
          : cards.map((card) => <PortfolioItem key={card.id} {...card} />)}
      </div>
    </div>
  );
}

cardReducer.js

const initialState = {
  cards: [],
  loading: true
};

export default function (state = initialState, action) {
  switch (action.type) {
    case GET_CARDS:
      return {
        ...state,
        users: action.payload,
        loading: false
      };
    case CARDS_ERROR:
      return {
        loading: false,
        error: action.payload
      };
    default:
      return state;
  }
}

完整代码如下:https://codesandbox.io/s/naughty-mcclintock-di9bb?file=/src/cardsActions.js

看起来你在 redux store 中将卡片添加到了错误的密钥:

case GET_CARDS:
  return {
    ...state,
    users: action.payload, // <-- users isn't accessed in UI
    loading: false
  };

不过您可以访问 state.cardsList.cards。将负载保存到您所在州的 cards 部分。

case GET_CARDS:
  return {
    ...state,
    cards: action.payload, // <-- save payload to cards state
    loading: false
  };

我不得不模拟一个 JSON API 端点,但只需将其换掉就可以让我继续跟踪您的代码。除非您的特定本地服务器设置有任何问题(即假设您的服务器正确提供 portfolio-data.json 文件),这应该至少解决您的更新状态和 UI 问题。