我有一个从我的后端获取一些信息的操作,执行以下操作:
export const getGroup = id => dispatch => {
axios
.get(`/api/group/${id}`)
.then(res => {
if (res.data === null) {
throw { error: "no group found" };
}
dispatch({
type: GET_GROUP,
payload: res.data
});
})
.catch(err =>
dispatch({
type: GET_ERRORS,
payload: err
})
);
};
我使用 mapStateToProps 映射数据,并使用解构将数据分配给一个变量 -
const { group } = this.props.group;
console.log(group) 给了我这个:
{passwordenabled: true, _id: "5b04a644533447437c4bb4a7", groupname: "ddsafdsfadfas", email: "[email protected]", password: "$2a$10$qXZsWtyhySGv4hrSCIXq2.0Yl9kjK8qYLUPkNPo1LfjZujbNeED.W", …}
但是,当我尝试访问 groupname 属性时,它给了我这个错误:
TypeError: Cannot read property 'groupname' of undefined
console.log 中的对象包含属性 groupname: "ddsafdsfadfas" 和 typeof 显示对象,但我仍然无法直接访问该属性。我不明白为什么我会收到这个错误?
编辑:完整的 mapStateToProps 代码 -
const mapStateToProps = state => ({
group: state.group,
errors: state.errors
});
export default connect(mapStateToProps, { getGroup })(Dashboard);
您的问题可能是异步对象。您正在尝试访问由异步操作提供的对象的值。尝试一些律检查,看看。尝试
const { group } = this.props.group;
if(group) {
console.log('The groupname is', group.groupname);
}
你的控制台有没有被执行过?
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句