简体   繁体   English

无法从服务器获取对象数组

[英]Can't get array of object from server

I am writing a simple website which display a list of object from server 我正在写一个简单的网站,其中显示了服务器中的对象列表

server: index.js 服务器:index.js

var db = [{ username: 'admin', password: '1234', email: 'admin@gmail.com'}];
app.get('/getListAccount', (req, res)=>{
  res.send(db);
})

display: list.js 显示:list.js

import React from 'react';
import {connect} from 'react-redux';
import axios from 'axios';

class Transaction extends React.Component{

  render(){
    var {listUser} = this.props;
    var xhtml = listUser != null ? <p>{listUser.map((e, i)=><p key={i}>{e.username}</p>)}</p>: <p>No user</p>;
    return (
      <div>
        <h1>Transaction</h1>
        {xhtml}
      </div>
    );
  }

  componentDidMount()
  {
    var {dispatch} = this.props;
    axios.get('/getListAccount')
    .then( ({data}) => {
      dispatch({
       type: 'INIT_LIST',
       mang: data
      });
    })
    .catch(err => console.log(err));
  }
}

module.exports = connect(function(state){
  return {listUser: state.listUser}
})(Transaction);

Here is reducer for listUser state: app.js 这是listUser状态的简化器: app.js

var listUser = (state = [{username: null, password: null, email: null}], 
action) => {
  switch(action.type){
    case 'INIT_LIST':
    {
      return {...action.mang};
    }
    default:
      return state;
  }
}

But when I run it always throw this error listUser.map is not a function . 但是当我运行它时,总是抛出此错误listUser.map is not a function Why and how can I fix it? 为什么以及如何解决? Thank you in advance! 先感谢您!

In your reducer, try doing 在减速器中,尝试做

case 'INIT_LIST':
    {
      return action.mang;
    }

The problem here is that you're putting an array in state (default state as well) and you're converting it back to the object. 这里的问题是,您将数组置于状态(也为默认状态),并将其转换回对象。

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

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