所以我试图用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)
所以看起来不错,但事实并非如此。 我接下来要做的就是将prop类型更改为:
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 post结果中的日志也表明res.data的类型是object。 除此之外,我可能还会做很多错误的事情,但这是我这次不知道的事情。
谢谢您的帮助!
答案 0 :(得分:0)
所以我找到了解决方案。我必须修改reducer的返回值以返回action.payload而不是{... state,groups:action.payload} 减速器代码现在变为:
import { GET_GROUPS_OF_USER } from '../actions/types';
export default function(state = [], action){
switch(action.type){
case GET_GROUPS_OF_USER:
return action.payload;
default:
return state;
}
}