所以我试图用redux返回一个数组,直到现在还没有多大成功。
我尝试记录操作有效负载,直到那时,它似乎还可以,但是当我实际更新状态时,它返回一个嵌套对象而不是有效负载中的数组。
同时,我修改了 proptype 以获取数组,但我收到提供对象而不是数组的错误消息,这是另一个问题。
这是我的减速器:
import { GET_GROUPS_OF_USER } from '../actions/types';
const initialState = {
groups: []
};
export default function(state = initialState, action){
console.log(action.payload);
switch(action.type){
case GET_GROUPS_OF_USER:
return {
...state,
groups: action.payload
};
default:
return state;
}
}
日志说:
[{…}]
0: {members: Array(1), _id: "5f69b4d9ba1b01fcc4736a85", name: "asd"}
length: 1
__proto__: Array(0)
所以看起来不错,但事实并非如此。我做的下一件事是将道具类型更改为:
Dashboard.propTypes = {
auth: PropTypes.object.isRequired,
groups: PropTypes.array.isRequired,
getGroupsOfUser: PropTypes.func.isRequired
}
这是我获取组的操作:
import axios from 'axios';
import { SERVER_ADDR } from '../config/keys';
import {
GET_GROUPS_OF_USER,
GET_ERRORS
} from './types';
export const getGroupsOfUser = data => dispatch => {
axios.post(SERVER_ADDR + '/group/get', data).then(res => {
console.log(typeof(res.data));
dispatch({
type: GET_GROUPS_OF_USER,
payload: res.data
});
}).catch(err => {
console.log(err);
dispatch({
type: GET_ERRORS,
payload: err.response.data
});
}
);
};
我在道具中得到的结果如下:
{auth: {…}, groups: {…}, getGroupsOfUser: ƒ}
auth: {isAuthenticated: true, user: {…}}
getGroupsOfUser: ƒ ()
groups:
groups: [{…}]
__proto__: Object
__proto__: Object
这就是我在获得结果后注销 this.props 的方式:
componentDidMount(){
const data = {
id: this.props.auth.user.id
}
this.props.getGroupsOfUser(data);
}
componentWillReceiveProps(nextProps) {
console.log(nextProps);
if (nextProps.groups) {
this.props = nextProps;
}
}
axios 发布结果中的日志显示 res.data 的类型是对象,即使服务器肯定返回了一个数组。除此之外,我可能也做错了很多事情,但这是我这次无法弄清楚的。
谢谢您的帮助!