简体   繁体   English

React组件无法通过API映射和呈现数组中的数据

[英]React component cannot map and render data in an array from an API

I'm using react, redux, axios, and redux-thunk to handle async. 我正在使用react,redux,axios和redux-thunk处理异步。

I have a feeling that the solution is going to be obvious but for some reason, I am unable to map over an array of users (retrieved from a local express/node api) and render each user out. 我有一种解决方案将变得显而易见的感觉,但是由于某种原因,我无法映射一组用户(从本地express / node api中检索)并渲染每个用户。 The user's info will be logged into the console but the... 用户的信息将被登录到控制台,但是...

<p>NO USERS FOUND</p> 

...component is rendered onto the screen instead. ...组件将呈现在屏幕上。

Here is my repo: https://github.com/tedjames/reduxTest 这是我的仓库: https : //github.com/tedjames/reduxTest

And here is what my component looks like: 这是我的组件的外观:

import React, { Component } from 'react';
import { connect } from 'react-redux'
import { getUsers } from '../redux/actions'

class App extends Component {
  componentWillMount() {
    console.log(this.props);
    this.props.getUsers();
  }

  render() {
    if (this.props.users[1]) {
      this.props.users.map((user) => {
        console.log("USER FOUND!");
        console.log(user.email);
        return <p key={user.id}>USER FOUND: {user.email}</p>
      });
    } else {
      return <p>NO USERS FOUND</p>
    }
  }
}

const mapStateToProps = state => {
  return {
    users: state.admin.users
  };
};

export default connect(mapStateToProps, { getUsers })(App);

And this is my action that uses axios to fetch the users: 这是我使用axios来获取用户的操作:

import axios from 'axios'
import { GET_USERS } from './types'

export const getUsers = () => {
  return (dispatch) => {
    axios.get('http://localhost:3090/users')
      .then(res => {
        console.log("<-- // DATA RECEIVED FROM SERVER // --> ");
        console.log(res);
        dispatch({ type: GET_USERS, payload: res.data })
      })
      .catch(({ response }) => {
        console.log("// ERROR RECEIVED FROM SERVER //");
        console.log(response);
      });
  }
};

This is what my console outputs 这是我的控制台输出

You have to return the array inside render (and wrap it in some tag): 您必须在render内部返回数组(并将其包装在一些标签中):

return (
  <div>{ this.props.users.map((user) => {
      console.log("USER FOUND!");
      console.log(user.email);
      return <p key={user.id}>USER FOUND: {user.email}</p> }
  </div> 
 );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM