我正在写一个简单的网站,显示来自服务器的对象列表
服务器: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 不是函数
。为什么以及如何修复它?先感谢您!
最佳答案
在你的reducer中,尝试做
case 'INIT_LIST':
{
return action.mang;
}
这里的问题是您将数组置于状态(默认状态也是如此),然后将其转换回对象。
关于javascript - 无法从服务器获取对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47429779/