从 useSelector 获取数据后无法显示信息

时间:2021-05-26 17:36:09

标签: reactjs redux

我正在尝试使用 Redux 从我的 API 访问数据,但是当 redux 工具包向我显示它是一个空数组时。我使用邮递员填充的 api 和 post 方法似乎工作得很好,但尝试使用 get 方法访问该数据时,它显示一个空数组。我的数据库虽然有数据。我的数据是一个对象数组,即[ {...} , {...} , {...} ]

API

import axios from "axios";

const url = "http://localhost:5000/info"

export const fetchInfo = () => axios.get(url);
export const createInfo = (newInfo) => axios.post(url, newInfo);

行动

import * as api from "../api/index.js";

//constants

import { FETCH_ALL, CREATE } from "../constants/actiontypes";

export const getInfo = () => async (dispatch) => {
  try {
    const { data } = await api.fetchInfo();
    console.log(data);
    dispatch({ type: FETCH_ALL, payload: data });
  } catch (error) {
    console.log(error);
  }
};

export const createInfo = (info) => async (dispatch) => {
  try {
    const { data } = await api.createInfo(info);
    dispatch({ type: CREATE, payload: data });
  } catch (error) {
    console.log(error);
  }
};

减速器

import { FETCH_ALL, CREATE } from "../constants/actiontypes";

export default (infos = [], action) => {
  switch (action.type) {
    case FETCH_ALL:
      return action.payload;
    case CREATE:
      return [...infos, action.payload];

    default:
      return infos;
  }
};

组合减速器

import {combineReducers} from "redux";
import infos from "./info"

export default combineReducers({infos})

我试图在其中显示的组件

import React from "react";
//redux
import { useSelector } from "react-redux";
//component
import MovieDetail from "./MovieDetail"

    const MovieTitles = () => {
      const infos = useSelector((state) => state.infos);
      console.log(infos)  // shows me empty array
      return (
        <div>
        
          {infos.map((i) => (
            <MovieDetail info={i} />
          ))}
        </div>
      );
    };
    export default MovieTitles;

还有什么我遗漏的东西可以让我访问数据吗? 谢谢

0 个答案:

没有答案