Redux 状态为空

Redux state is empty

我正在按照一个 redux 示例在 react-redux 中创建一个切片,在我的控制台中我没有错误并且状态有我的容器但它只是空的并且没有来自我的 axios 的任何数据 api称呼, 我的后端是 运行 并且 api 调用工作正常。

容器切片:

import { createSlice } from "@reduxjs/toolkit";
import { api } from "../components/pages/screens/HomeScreen";
const vesselSlice = createSlice({
  name: "vessels",
  initialState: {
    vessels: [],
  },
  reducers: {
    getVessels: (state, action) => {
      state.vessels = action.payload;
    },
  },
});
export const vesselReducer = vesselSlice.reducer;
const { getVessels } = vesselSlice.actions;

export const fetchVessels = () => async (dispatch) => {
  try {
    await api
      .get("/vessels")
      .then((response) => dispatch(getVessels(response.data)));
  } catch (e) {
    return console.error(e.message);
  }
};

主屏幕:

import React, { useEffect } from "react";
import VesselCard from "../../VesselCard";
import axios from "axios";
import { useDispatch, useSelector } from "react-redux";
import { vesselSlice } from "../../../features/vesselSlice";
export const api = axios.create({
  baseURL: "http://127.0.0.1:8000/api/vessels/info",
  headers: {
    "Content-Type": "application/json",
  },
});
function HomeScreen() {
  const { vessels, isLoading } = useSelector((state) => state.vessels);
  return (
    <div>
      Fleet vessels :
      <div className="fleet-vessels-info">
        {vessels.map((vessel) => (
          <VesselCard vessel={vessel} />
        ))}
      </div>
    </div>
  );
}

export default HomeScreen;

您必须实际调用函数 fetchVessels。在这个简单的例子中,我会使用 useEffect:

import React, { useEffect } from "react";
import VesselCard from "../../VesselCard";
import axios from "axios";
import { useDispatch, useSelector } from "react-redux";
import { vesselSlice, fetchVessels } from "../../../features/vesselSlice";
export const api = axios.create({
  baseURL: "http://127.0.0.1:8000/api/vessels/info",
  headers: {
    "Content-Type": "application/json",
  },
});
function HomeScreen() {
  const { vessels, isLoading } = useSelector((state) => state.vessels);
  const dispatch = useDispatch();

  // This part:
  useEffect(() => {
    fetchVessels(dispatch);
  }, [dispatch]);

  return (
    <div>
      Fleet vessels :
      <div className="fleet-vessels-info">
        {vessels.map((vessel) => (
          <VesselCard vessel={vessel} />
        ))}
      </div>
    </div>
  );
}

export default HomeScreen;