我需要在动态变化的嵌套对象值上设置状态我不确定如何做到这一点,这是我尝试过的。
const [userRoles] = useState(null);
const { isLoading, user, error } = useAuth0();
useEffect(() => {
console.log(user);
// const i = Object.values(user).map(value => value.roles);
// ^ this line gives me an react error boundary error
}, [user]);
// This is the provider
<UserProvider
id="1"
email={user?.email}
roles={userRoles}
>
用户对象如下所示:
{
name: "GGG",
"website.com": {
roles: ["SuperUser"],
details: {}
},
friends: {},
otherData: {}
}
我需要获取角色值,但每次调用 api 时它的父级“website.com”都会发生变化,因此我需要找到一种搜索角色的方法。
答案 0 :(得分:1)
您可以搜索键为roles
的元素的值,如果找到,返回roles
值,否则返回undefined
。
Object.values(user).find(el => el.roles)?.roles;
注意:我完全同意其他人的观点,即您应该寻求规范化您的数据,以不使用任何动态生成的属性键。
const user1 = {
name: "GGG",
"website.com": {
roles: ["SuperUser"],
details: {}
},
friends: {},
otherData: {}
}
const user2 = {
name: "GGG",
friends: {},
otherData: {}
}
const roles1 = Object.values(user1).find(el => el.roles)?.roles;
const roles2 = Object.values(user2).find(el => el.roles)?.roles;
console.log(roles1); // ["SuperUser"]
console.log(roles2); // undefined
答案 1 :(得分:1)
我认为您需要修改对象的形状。我觉得奇怪的是有些键似乎是固定的,但一个似乎是可变的。动态键可能非常有用,但这似乎不是使用它们的正确位置。我建议您将用户对象的形状更改为如下所示:
{
name: "GGG",
site: {
url: "website.com",
roles: ["SuperUser"],
details: {}
},
friends: {},
otherData: {}
}
在您的特定用例中,固定键将为您省去很多麻烦。
答案 2 :(得分:1)
我会推荐其他人所说的关于您的数据对象中没有动态键的内容。
为了更新复杂的对象状态,我知道如果您使用 React Hooks,您可以使用扩展运算符并基本上克隆状态并使用更新版本更新它。 React hooks: How do I update state on a nested object with useState()?