javascript - Uncaught TypeError: Cannot read properties of undefined (reading 'length') - Stack Overflow

I am developing a react app, but i am facing this error-> "Uncaught TypeError: Cannot read prop

I am developing a react app, but i am facing this error-> "Uncaught TypeError: Cannot read properties of undefined (reading 'length')". how to fix this? my code is:

import React from "react";
import { Grid, CircularProgress } from "@material-ui/core";
import Post from "./Post/Post";
import useStyles from "./styles";
import { useSelector } from "react-redux";

const Posts = () => {
  const posts = useSelector((state) => state.Posts);
  const classes = useStyles();

  console.log(posts);
  return (!posts.length ? <CircularProgress/> :(
   <Grid className={classes.container} container alignItems="stretch" spacing={3}>
      {
        posts.map((post)=> (
              <Grid key={post._id} item xs={12} sm={6}>
                <Post post = {post} />
              </Grid>
        ))
      }

   </Grid>
 )
  );
};

export default Posts;

I am developing a react app, but i am facing this error-> "Uncaught TypeError: Cannot read properties of undefined (reading 'length')". how to fix this? my code is:

import React from "react";
import { Grid, CircularProgress } from "@material-ui/core";
import Post from "./Post/Post";
import useStyles from "./styles";
import { useSelector } from "react-redux";

const Posts = () => {
  const posts = useSelector((state) => state.Posts);
  const classes = useStyles();

  console.log(posts);
  return (!posts.length ? <CircularProgress/> :(
   <Grid className={classes.container} container alignItems="stretch" spacing={3}>
      {
        posts.map((post)=> (
              <Grid key={post._id} item xs={12} sm={6}>
                <Post post = {post} />
              </Grid>
        ))
      }

   </Grid>
 )
  );
};

export default Posts;
Share Improve this question asked Feb 21, 2022 at 4:51 MahidMahid 91 gold badge1 silver badge3 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 1

use !post || !post.length or !posts?.length

The error says the type of posts is Undefined. As you are getting that value from Posts in state object, that means that Posts is not initialized in your state. Try initializing "Posts" with empty Array([]) in your initial state object.

You can try something like this , !posts?.length > -1 ?. As you are checking if the post array is empty or not.

try posts && <Grid>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745105556a4611533.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信