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
4 Answers
Reset to default 1use !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条)