无法从服务器获取对象数组
我正在写一个简单的网站,显示从服务器的对象列表
服务器: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
。 为什么以及如何解决? 先谢谢你!
在你的减速器中,试着做
case 'INIT_LIST': { return action.mang; }
这里的问题是你把一个数组置于状态(默认状态),并将其转换回对象。