无法在 redux 中使用 get 请求获取元素

问题描述

我是 redux 的新手,我想使用 GET 请求 API 获取列表。 获取的数据如下:

[
 {
    "_id": "608bac98e16977cc172a5bf4","username": "Saranya","description": "desc Now","title": "NaN","createdAt": "2021-04-30T07:07:04.938Z","updatedAt": "2021-04-30T07:07:04.938Z","__v": 0
  },{
    "_id": "608bf8c9878cf0b7e85ead9e","description": "desss","title": "aeaa","date": "2021-12-03T18:30:00.000Z","createdAt": "2021-04-30T12:32:09.618Z","updatedAt": "2021-04-30T12:32:09.618Z",{
    "_id": "608c0aef6bb6f3d56acd63b0","instructions": "new instruct","time": "1pm to 2pm","type": "want","createdAt": "2021-04-30T13:49:35.715Z","updatedAt": "2021-04-30T13:49:35.715Z",{
    "_id": "608c0df87d8510d6ffcc0157","username": "Saran","description": "daaaa","title": "title111","instructions": "instructions for tst","time": "8pm to 9pm","type": "food","date": "2021-05-03T14:01:41.000Z","createdAt": "2021-04-30T14:02:32.439Z","updatedAt": "2021-04-30T14:02:32.439Z","__v": 0
  }
]

动作文件authActions.js文件是:

import setAuthToken from "../utils/setAuthToken";
import jwt_decode from "jwt-decode";
import axios from "axios";


import { GET_ERRORS,SET_CURRENT_USER,USER_LOADING,GET_TodoS,FETCH_SUCCESS,FETCH_FAILURE } from "./types";

export const getTodos = () =>
 dispatch => {
  dispatch({type: GET_TodoS});

   axios({
      url: 'http://localhost:5000/postad/listing',method: 'GET',})
    .then(response => {
      console.log(response.data);
      const data = response.data;
      dispatch({type: FETCH_SUCCESS,payload:{
        data
      }});
    })
    .catch(error => {
      console.log(error);
      dispatch({type: FETCH_FAILURE})
    });
}

types.js 文件

export const USER_LOADING = "USER_LOADING";
export const GET_ERRORS = "GET_ERRORS";
export const SET_CURRENT_USER = "SET_CURRENT_USER";
export const USERS_ERROR = 'USERS_ERROR';
export const GET_TodoS = 'GET_TodoS';
export const FETCH_SUCCESS = 'FETCH_SUCCESS';
export const FETCH_FAILURE = 'FETCH_FAILURE';

reducers 文件 authReducer.js 是

import { SET_CURRENT_USER,FETCH_FAILURE } from "../actions/types";

const isEmpty = require("is-empty");

const initialState = {
  isAuthenticated: false,user: {},todos: [],loading: false,data: null,showSuccessModal: false
};


export default function(state = initialState,action) {
  switch (action.type) {
    case SET_CURRENT_USER:
      return {
        ...state,isAuthenticated: !isEmpty(action.payload),user: action.payload
      };
    case USER_LOADING:
      return {
        ...state,loading: true
      };
      case GET_TodoS:
      return {
        ...state,loading: true
      };
    case FETCH_SUCCESS:
      return {
        ...state,todos: action.payload.data,loading: false
      };
    case FETCH_FAILURE:
      return {
        ...state,error: action.error
      };
    default:
      return state;
  }
}

显示数据的列表文件

import React,{ Component } from 'react';
import Dashboard from "./Dashboard";
import { connect } from 'react-redux';
import { getTodos } from "../../actions/authActions";

import List from '../../components/List';

class Mylisting extends Component {

  componentDidMount = () => {
    this.props.getTodos();
      console.log(this.props.getTodos());
  }

  render() {
        let listings = [];
        if (this.props.todos && this.props.todos.length > 0) {
    listings = this.props.todos.map((owner) => {
        return (
            <List key={owner._id} owner={owner} {...this.props} />
        )
    })
    console.log(listings);
}
        return (
          <div>
          <Dashboard />
                <div>
                        <table responsive striped>
                            <thead>
                                <tr>
                                    <th>UserName</th>
                                    <th>Desceiption</th>
                                    <th>Title</th>
                                </tr>
                            </thead>
                            <tbody>
                                {listings}
                            </tbody>
                        </table>
          </div>
          </div>
        )
    }
}

const mapStatetoProps = state => {
  console.log(state.todo);
  console.log(state.todos);
  const { todos } = state;


  return {
    todos
  };
};

const mapdispatchToProps = dispatch => ({
  getTodos: () => dispatch(getTodos())
});

export default connect(mapStatetoProps,mapdispatchToProps)(Mylisting);

List.js 文件

import React,{ Component } from 'react';

    const List = (props) => {
        return (
    
    
                <tr>
                    <td>{this.props.username}</td>
                    <td>{this.props.description}</td>
                    <td>{this.props.title}</td>
                </tr>
              
    
        )
    }
    export default List;

App.js 文件

import Landing from "./components/layout/Landing";
import Register from "./components/auth/Register";
import Login from "./components/auth/Login";
import PrivateRoute from "./components/private-route/PrivateRoute";
import Dashboard from "./components/dashboard/Dashboard";
import Postad from "./components/dashboard/post-ad";
import Mylist from "./components/dashboard/my-listings";

import "./App.css";

// Check for token to keep user logged in
if (localStorage.jwtToken) {
  // Set auth token header auth
  const token = localStorage.jwtToken;
  setAuthToken(token);
  // Decode token and get user info and exp
  const decoded = jwt_decode(token);
  // Set user and isAuthenticated
  store.dispatch(setCurrentUser(decoded));
  // Check for expired token
  const currentTime = Date.Now() / 1000; // to get in milliseconds
  if (decoded.exp < currentTime) {
    // logout user
    store.dispatch(logoutUser());

    // Redirect to login
    window.location.href = "./login";
  }
}
class App extends Component {
  render() {
    return (
      <Provider store={store}>
        <Router>
          <div className="App">
            <Route exact path="/" component={Landing} />
            <Route exact path="/register" component={Register} />
            <Route exact path="/login" component={Login} />
            <Route exact path="/create" component={Postad} />
            <Route exact path="/list" component={Mylist} />

            <Switch>
              <PrivateRoute exact path="/dashboard" component={Dashboard} />
            </Switch>
          </div>
        </Router>
      </Provider>
    );
  }
}
export default App;

定义了所有相关文件。列表文件是空白的,没有显示任何数据。如何使用获取请求 API 获取前面提到的数据。知道这些文件中缺少什么吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)