Kev*_*vvv 1 javascript destructuring ecmascript-6 reactjs
我有以下解构:
const {
user: {
username,
image,
uid
} = {},
gallery: {
image: picture,
} = {},
} = data
Run Code Online (Sandbox Code Playgroud)
问题是gallery有时null(不是picture内部gallery),即使我需要的是picture内部gallery存在时。换句话说,gallery: null,不是gallery.image: null。
因此,我得到:
null 不是对象
的错误消息gallery.image。
我如何有条件地解构以便gallery.image在它存在时使用它,但gallery在为空时不解构?
回退仅在值是undefined但不是null
const data = {
user: {
username: 'Alice',
image: 'alice.png',
uid: 1
},
gallery: undefined
};
const {
user: {
username,
image,
uid
} = {},
gallery: {
image: picture,
} = {},
} = data;
console.log(username, image, uid, picture);Run Code Online (Sandbox Code Playgroud)
const data = {
user: {
username: 'Alice',
image: 'alice.png',
uid: 1
},
gallery: null
};
const {
user: {
username,
image,
uid
} = {},
gallery: {
image: picture,
} = {},
} = data;
console.log(username, image, uid, picture);Run Code Online (Sandbox Code Playgroud)
null给{}你破坏它像在此之前:const data = {
user: {
username: 'Alice',
image: 'alice.png',
uid: 1
},
gallery: null
};
const {
user: {
username,
image,
uid
} = {},
gallery: {
image: picture,
}
} = {...data, gallery: data.gallery || {}};
console.log(username, image, uid, picture);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1848 次 |
| 最近记录: |