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

Reactjs 无法在redux中使用get请求获取元素,reactjs,redux,react-redux,get,axios,Reactjs,Redux,React Redux,Get,Axios,我是redux新手,我想使用GET请求API获取列表。 要获取的数据如下所示: [ { "_id": "608bac98e16977cc172a5bf4", "username": "saranya", "description": "desc now", "title": "NaN", &quo

我是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",
    "username": "saranya",
    "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",
    "__v": 0
  },
  {
    "_id": "608c0aef6bb6f3d56acd63b0",
    "username": "saranya",
    "description": "desss",
    "title": "aeaa",
    "instructions": "new instruct",
    "time": "1pm to 2pm",
    "type": "want",
    "date": "2021-12-03T18:30:00.000Z",
    "createdAt": "2021-04-30T13:49:35.715Z",
    "updatedAt": "2021-04-30T13:49:35.715Z",
    "__v": 0
  },
  {
    "_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
  }
]
操作文件authoctions.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})
    });
}
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';
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;
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;
还原程序文件authReducer.js是

import { SET_CURRENT_USER, USER_LOADING,GET_TODOS,FETCH_SUCCESS,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,
         loading: false,
         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);
import React,{Component}来自'React';
从“/Dashboard”导入仪表板;
从'react redux'导入{connect};
从“../../actions/authActions”导入{getTodos};
从“../../components/List”导入列表;
类Mylisting扩展了组件{
componentDidMount=()=>{
this.props.gettoos();
log(this.props.gettoos());
}
render(){
让清单=[];
if(this.props.todos&&this.props.todos.length>0){
listings=this.props.todos.map((所有者)=>{
返回(
)
})
console.log(列表);
}
返回(
用户名
描述
标题
{listings}
)
}
}
常量mapStateToProps=状态=>{
console.log(state.todo);
console.log(state.todos);
const{todos}=状态;
返回{
待办事项
};
};
const mapDispatchToProps=调度=>({
getTodos:()=>dispatch(getTodos())
});
导出默认连接(MapStateTrops、mapDispatchToProps)(Mylisting);
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';
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;
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;
import React,{Component}来自'React';
常量列表=(道具)=>{
返回(
{this.props.username}
{this.props.description}
{this.props.title}
)
}
导出默认列表;
App.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';
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;
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;
从“/components/layout/Landing”导入平台;
从“/components/auth/Register”导入寄存器;
从“/components/auth/Login”导入登录名;
从“/components/private route/private route”导入private路由;
从“/components/Dashboard/Dashboard”导入仪表板;
从“/components/dashboard/post ad”导入Postad;
从“/components/dashboard/my listings”导入Mylist;
导入“/App.css”;
//检查令牌以保持用户登录
if(localStorage.jwtToken){
//设置身份验证令牌头身份验证
const token=localStorage.jwtToken;
setAuthToken(令牌);
//解码令牌并获取用户信息和exp
const decoded=jwt_decode(令牌);
//设置用户并进行身份验证
存储调度(setCurrentUser(已解码));
//检查过期的令牌
const currentTime=Date.now()/1000;//以毫秒为单位
if(decoded.exp

所有相关文件都已定义。列表文件为空,不显示任何数据。如何使用get request API获取前面提到的数据。知道这些文件中缺少什么吗?

Hey!我想问题就在这里。。。你发了太多次了。export const getTodos=()=>axios('=>{console.log(response.data);const data=response.data;dispatch({type:FETCH_SUCCESS,payload:{data}});}).catch(error=>{console.log(error);dispatch({type:FETCH_FAILURE});}那么需要做什么呢?