【问题标题】:How can I push the state to an array with specific items?如何将状态推送到包含特定项目的数组?
【发布时间】:2020-04-10 07:57:48
【问题描述】:

我的大部分项目都处于我想将其推送到数组中的状态

我想将所有状态推送到某些项目之外

这是我的状态

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);
  };

【问题讨论】:

标签: javascript arrays reactjs react-native


【解决方案1】:

如果您不想使用任何库,可以使用destructuring assignmentrest 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',
]));

【讨论】:

  • 我不是投反对票的人,尽管您的答案与重复候选人中描述的 3 种方式完全相同。如果 SO 上已经有很好的问题和答案,我们不应该再回答。
  • @EmileBergeron 我认为不应该在没有反馈的情况下允许投反对票,因此我会在任何时候发现所有帖子都系统地获得无评论投反对票的情况时重新创建答案。
  • 这只会让您的帐户被禁止并惹恼管理员,从长远来看,我认为这不是一个好主意。并且在投票时强制发表评论已经是discussedalot
  • (我最终还是选择了投票,因为这是目前最完整的答案)
【解决方案2】:

如果你想选择一些属性,那么只需声明你想要的属性:

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);

【讨论】:

  • 您最初的回答是无效的语法。我删除了我的反对票,虽然这个问题应该作为一个骗子关闭,但是已经有很多类似的答案了。
【解决方案3】:

你可以使用解构赋值 如图所示 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);

你可以阅读更多关于它的信息hereand herealso here 加上很好的例子

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-02
    • 1970-01-01
    • 2017-12-08
    • 2019-01-08
    • 2020-12-10
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    相关资源
    最近更新 更多