我的大部分状态都想将其推送到数组中
我想将所有状态都推到除某些项目之外
这是我的状态
state = {
username: '..',
date: '..',
time: '..',
description: '..',
images: '..',
buildingNumber: '..',
status: '..',
serviceDB: '..',
snapshotKey: '..', // i don't need this when pushed
count: -1, // i don't need this when pushed
};
这是我的代码
let order = [];
order.push(this.state);
console.log(order); it's log all state
// I want to push it to DB
database()
.ref(`Providers/ProvidersOrders/${uid}`)
.push(...order);
};
答案 0 :(得分:1)
如果不使用任何库就可以使用destructuring assignment和rest parameters syntax:
const { snapshotKey, count, ...rest } = this.state;
...
order.push(rest);
否则,您也可以使用Lodash的_.omit
函数:
order.push(_.omit(this.state, ['snapshotKey', 'count']));
或者,如果要选择要使用的属性,则可以再次使用解构和shorthand property names创建对象:
const {
username,
date,
time,
description,
images,
buildingNumber,
status,
serviceDB,
} = this.state;
...
order.push({
username,
date,
time,
description,
images,
buildingNumber,
status,
serviceDB,
});
或者与Lodash一起使用_.pick
,与_.omit
相反:
order.push(_.pick(this.state, [
'username',
'date',
'time',
'description',
'buildingNumber',
'status',
'serviceDB',
]));
答案 1 :(得分:0)
如果要选择一些属性,则只需声明所需的属性即可:
let {snapshotKey, count, ...y} = state;
arr.push(y);
一个例子:
state = {
username: '1',
date: '2',
time: '3',
description: '4',
images: '5',
buildingNumber: '6',
status: '7',
serviceDB: '8',
snapshotKey: '9', // i don't need this when pushed
count: -10, // i don't need this when pushed
};
let arr = [];
let {snapshotKey, count, ...y} = state;
arr.push(y);
console.log(arr);
答案 2 :(得分:0)
您可以使用解构分配 如图所示 documentation
const { count,snapshotKey, ...newData } = this.state;
现在,newData包含:
newData={
username: '..',
date: '..',
time: '..',
description: '..',
images: '..',
buildingNumber: '..',
status: '..',
serviceDB: '..',
};
现在在newData中使用
database()
.ref(`Providers/ProvidersOrders/${uid}`)
.push(...newData);