[英]iterate over map json in react
我在嘗試使用來自此類 json 的數據時遇到了一些問題
{
"content_module": {
"authz.provider_3": [
"User 10",
"User 11",
"User 18",
"User 2",
"User 3",
"User 5"
],
"authz.provider_2": [
"User 13",
"User 15",
"User 16",
"User 17",
"User 8",
"User 9"
],
"authz.provider_4": [
"User 0",
"User 1",
"User 12",
"User 19",
"User 6",
"User 7"
],
"authz.provider_1": [
"User 14",
"User 4"
]
},
"auth_module": {
"authn.provider_4": [
"User 2",
"User 5",
"User 9"
],
"authn.provider_2": [
"User 1",
"User 10",
"User 13",
"User 14",
"User 16",
"User 18",
"User 6",
"User 8"
],
"authn.provider_3": [
"User 0",
"User 11",
"User 12",
"User 15",
"User 7"
],
"authn.provider_1": [
"User 17",
"User 19",
"User 3",
"User 4"
]
}
}
我在 react 中使用 axios,但是當我執行 get 方法並將數據存儲在 state 中時,然后當我嘗試使用 forEach 方法時,我收到此類錯誤。
Objects are not valid as a React child (found: object with keys {authz.provider_3, authz.provider_2, authz.provider_4, authz.provider_1}). If you meant to render a collection of children, use an array instead.
這是獲取方法:
const [contentModules, setContentModules] = useState([]);
useEffect(() => {
axios.get('http://localhost:8080/usuarios/filtrados')
.then(res => {
setContentModules(res.data.content_module);
setAuthModules(res.data.auth_module);
})
.catch(err => {
console.log(err);
})
}, [])
錯誤很明顯,如果要循環整個模塊,則不能使用 forEach 在 object 上循環,可以使用Object.values(res.data.content_module)
將返回 ZA3CBC3F9D0CE2F2F2C1554E1B6 數組 [7154E1B6 [[],[],[]]
7154E1B6] [[],[],[]]
或者如果你想循環鍵使用Object.keys(res.data.content_module)
將返回鍵數組 ["authz.provider_1", "authz.provider_2"]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.