【问题标题】:Can't get array of object from server无法从服务器获取对象数组
【发布时间】:2017-11-22 16:28:56
【问题描述】:

我正在编写一个简单的网站,显示来自服务器的对象列表

服务器:index.js

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

显示: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);

这是listUser 状态的reducer: app.js

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

但是当我运行它时总是抛出这个错误 listUser.map is not a function。为什么以及如何解决?先感谢您!

【问题讨论】:

  • 您得到什么响应(即 componentDidMount 中的数据)?你能检查一下你的网络标签并告诉你吗?
  • map 是 Array 原型上的一个函数。所以最好检查 Array.isArray(listUser),而不是 listUser != null。
  • @AjayGaur 对getListAccount 的响应是[{"username":"admin","password":"1234","email":"admin@gmail.com"}],但它仍然抛出listUser.map is not a function

标签: javascript node.js reactjs redux axios


【解决方案1】:

在你的减速器中,尝试做

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

这里的问题是您将数组置于状态(默认状态也是如此),然后将其转换回对象。

【讨论】:

  • 哦,它就像一个魅力,非常感谢@Ajay Gaur。
  • @TuấnTrầnDuy 很高兴它可以工作,但更好的方法是将对象数组放入您的状态并使用 lodash map 函数,这样您就可以避免任何错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-08
  • 1970-01-01
  • 2016-08-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多