【问题标题】:How to make usestate back to default value如何使usestate恢复默认值
【发布时间】:2021-06-20 15:34:53
【问题描述】:

我有一个类似这样的使用状态

const [currentApp, setCurrentApp] = useState({})

currentApp 的输出是

{
    activity_name_id: ["1"]
    ceo_birthday: "1400-03-07"
    ceo_gender: "0"
    ceo_id_code: "2233323655666666555"
    ceo_photo: "/pic_user/userPic_1624200842.jpg"
    ceo_photo_id: "51"
    charity_id: "14"
    charity_verified: "0"
    website: null
    ....
}

列表取决于填充了多少字段,我想将所有这些设置为 '-' 我使用了此代码但不起作用

const newCurrentApp = Object.keys(currentApp).reduce((acc, field) => {
    acc[field] = ""
    return acc
}, {})

【问题讨论】:

  • 请提供一些示例输入和预期输出。
  • 您想将所有内容设置为'-' 吗?
  • @iota 我补充说
  • 预期输出是什么?
  • @PixAff 是的,我添加了currentApp的输出

标签: javascript reactjs react-hooks


【解决方案1】:

要将对象的所有值设置为'-',您可以直接遍历没有reduce的键并修改对象。

const currentApp = {
    activity_name_id: ["1"],
    ceo_birthday: "1400-03-07",
    ceo_gender: "0",
    ceo_id_code: "2233323655666666555",
    ceo_photo: "/pic_user/userPic_1624200842.jpg",
    ceo_photo_id: "51",
    charity_id: "14",
    charity_verified: "0",
    website: null
    // ...
};
Object.keys(currentApp).forEach(k => currentApp[k] = '-');
console.log(currentApp);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-17
    • 1970-01-01
    • 2017-11-12
    相关资源
    最近更新 更多