TypeError:无法读取未定义的属性"getPosts"-useQuery挂钩,对功能组件做出反应 [英] TypeError: Cannot read property 'getPosts' of undefined - useQuery hook, react Functional Components
问题描述
我确实尝试搜索相同的问题,但是所有这些问题都是有角度的或无关的
我正在尝试使用MongoDB,Express,React,Node,Graphql和Apollo制作一个社交应用程序,我正在观看freecodecamp的视频:
使调试更简单,
const {加载中数据:{getPosts:posts}} = useQuery(FETCH_POSTS_QUERY);
这样做:
const {数据,加载,错误} = useQuery(FETCH_POSTS_QUERY);if(data){console.log(data);const {getPosts:posts} =数据;}如果(错误){console.log(错误);返回错误";//阻止渲染}
这有效,但是当数据存在且并非总是存在时
不是当数据时",并非总是" ????奇怪...只有在存在 data
的情况下才能定义帖子" ...在未定义的情况下访问它会失败,总是...您必须检查"data"
您只能/应该在以下情况下渲染项目(帖子):
-
!loading
AND
-
data!=未定义
-if(data)
或(JSX中的data&
{正在加载&&< h1>正在加载帖子..</h1>}{data&&(< Transition.Group>{帖子&&posts.map((post)=>(< Grid.Column键= {post.id}样式= {{marginBottom:20}}>< PostCard post = {post}/></Grid.Column>))}</Transition.Group>)}
I did try searching for the same question but all of those were of either angular or unrelated,
I am trying to make a Social app using MongoDB, Express, React, Node, Graphql with Apollo, I am following a video from freecodecamp : Link to the video In that video everything worked fine but in his deployed version he is having the same error as mine
react_devtools_backend.js:2450 TypeError:
Cannot read property 'getPosts' of undefined
at ae (Home.js:14) at Jo (react-dom.production.min.js:3274)
My Code: I am dropping a link to my github repo containing the whole project : Link to github repo
Stack Overflow was throwing too many indentation issues so i have linked my github above as there is too much of code
- I'm using semantic-ui for styling
- I'm using graphql the fetch posts from MongoDB
- Apollo Client for rendering data
This is the error I am getting in the Home.js: Screen Shot of the error:
Make it simpler to debug, instead:
const { loading, data: { getPosts: posts } } = useQuery(FETCH_POSTS_QUERY);
do:
const { data, loading, error } = useQuery(FETCH_POSTS_QUERY);
if(data) {
console.log(data);
const { getPosts: posts } = data;
}
if(error) {
console.log(error);
return "error"; // blocks rendering
}
this works but not when data is there and not always
"not when data", "not always"??? weird ... 'posts' can be defined only if data
exists ... accessing it when undefined will fail, always ... you must check 'data'
You can/should render items (posts) ONLY when:
!loading
AND
data != undefined
-if(data)
or(data &&
in JSX{loading && <h1>Loading posts..</h1>} {data && ( <Transition.Group> {posts && posts.map((post) => ( <Grid.Column key={post.id} style={{ marginBottom: 20 }}> <PostCard post={post} /> </Grid.Column> ))} </Transition.Group> )}
这篇关于TypeError:无法读取未定义的属性"getPosts"-useQuery挂钩,对功能组件做出反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!