I'm trying to do a project, and this project has lists, each with a title, and when I use Map, I have this error:
Property 'map' does not exist on type 'List'
How can I solve the problem?
And this file shows all the lists and each list has been passed a title.
lists.tsx:
import { Grid } from "@material-ui/core";
import SingleList from "./single-list";
import { useStyle } from "../../../../styles/list-styles";
import Header from "../../header-footer/header";
import ListModal from "../modals/list-modal";
import { List } from "../../../../redux-store/reducers/todo-list-reducer";
import { useSelector } from "react-redux";
const Lists = () => {
const classes = useStyle();
// TS infers type: (state: RootState) => object
const selectListData = (state: List) => state;
// TS infers `lists` is object
const lists = useSelector(selectListData);
console.log("title-listData: ", lists);
return (
<>
<Header />
<Grid className={classes.grid}>
<Grid
container
className={classes.addButton}
item
direction="row-reverse"
>
<ListModal />
</Grid>
<Grid container item lg={12} direction="row" spacing={1}>
{lists.map((list: { title: string; }) => (
<Grid item lg={3} sm={6} xs={12}>
<SingleList title={list.title} />
</Grid>
))}
</Grid>
</Grid>
</>
);
};
export default Lists;
CodePudding user response:
Use Optional chaining (?.) for a check value of lists
. Array values available or not in the lists
variable. lists
is must be an Array format.
Or you cal also check with {Array.isArray(lists) && lists.length && lists.map( ...
{lists?.map((list: { title: string; }) => (
<Grid item lg={3} sm={6} xs={12}>
<SingleList title={list.title} />
</Grid>
))}
CodePudding user response:
if (lists instanceof Array) {
lists.map((item:{title:string}) => { });
}