React组件传参疑问:为何需两次调用props才能获取对象数组?
问题分析与解决
你之所以需要两次调用Post_postsData,核心是每一层组件传递props时都做了多余的嵌套包装,再加上MyPost组件里对props的命名或解构方式有误,才出现了重复的层级。
举个贴合你场景的例子,你的传递流程大概率是这样的:
- index.js传给App:
<App App_postsData={你的数组} /> - App.js传给Profile:
<Profile Profile_postsData={props.App_postsData} /> - Profile.jsx传给MyPost:
<MyPost Post_postsData={props.Profile_postsData} /> - 到了MyPost.jsx里,你可能直接把整个props对象命名成了
Post_postsData(比如写了function MyPost(Post_postsData) { ... }),而这个props对象里本身就有一个叫Post_postsData的属性(也就是Profile传过来的值),所以才需要Post_postsData.Post_postsData才能拿到Profile传递的内容,再往下取Profile_postsData.App_postsData才能最终拿到目标数组。
修正方法
每一层传递时直接传递数组本身,不要额外嵌套:
- index.js:
<App posts={你的数组} /> - App.js:
<Profile posts={props.posts} /> - Profile.jsx:
<MyPost posts={props.posts} /> - MyPost.jsx里直接使用:
let post = props.posts(或者用解构更简洁:function MyPost({ posts }) { let post = posts; ... })
这样就能彻底避免多层冗余嵌套,代码逻辑更直观清晰。
内容的提问来源于stack exchange,提问作者Maksymsly
相关产品推荐
相关产品推荐

