首页 > 解决方案 > 如何使usestate恢复默认值

问题描述

我有一个这样的使用状态

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
}, {})

标签: javascriptreactjsreact-hooks

解决方案


要将对象的所有值设置为'-',您可以直接遍历没有的键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);


推荐阅读