누구든지 React.js의 필터로 나를 도울 수 있는지 궁금합니다. 내 React 앱은 Pokemon API에서 내 데이터를 가져 오는 Node.js 앱에 연결되어 있습니다. 기본적으로 프런트 엔드 경로 / pokemon : id에 하나의 포켓몬 카드를 표시하고 싶습니다. 이렇게하려면 배열을 통해 필터링 한 다음 매핑합니다. 어떤 이유로 이것은 작동하지 않으며 누군가 내 코드를 확인하고 내가 간단한 실수를하고 있는지 확인할 수 있는지 궁금합니다. 나는 필터를 제거하면 모든 것이 작동하기 때문에 내 포켓몬 카드를 필터링하는 방식에 문제가 있다고 생각합니다. 코딩 한 지 3 개월 밖에되지 않았으니 엉성한 코드를 용서 해주세요!
import React, {useState} from "react";
import { useParams } from "react-router-dom";
import { makeStyles } from '@material-ui/core/styles';
import clsx from 'clsx';
import Card from '@material-ui/core/Card';
import CardHeader from '@material-ui/core/CardHeader';
import CardMedia from '@material-ui/core/CardMedia';
import CardContent from '@material-ui/core/CardContent';
import CardActions from '@material-ui/core/CardActions';
import Collapse from '@material-ui/core/Collapse';
import IconButton from '@material-ui/core/IconButton';
import Typography from '@material-ui/core/Typography';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
const useStyles = makeStyles((theme) => ({
root: {
maxWidth: 345,
},
media: {
height: 0,
paddingTop: '56.25%', // 16:9
},
expand: {
transform: 'rotate(0deg)',
marginLeft: 'auto',
transition: theme.transitions.create('transform', {
duration: theme.transitions.duration.shortest,
}),
},
expandOpen: {
transform: 'rotate(180deg)',
},
}));
const PokeDetail = ({ pokemon }) => {
const { id } = useParams();
const classes = useStyles();
const [expanded, setExpanded] = useState(false);
const handleExpandClick = () => {
setExpanded(!expanded);
};
return (
<div>
{pokemon.length >= 1 &&
pokemon
.filter((poke) => {
return poke.id === id
})
.map((poke) => (
<div>
<Card className={classes.root}>
<CardHeader
title={poke.name.english}
subheader={poke.type}
/>
<CardMedia
className={classes.media}
image="/Images/"
title={poke.name.english}
/>
<CardContent>
<Typography variant="body2" color="textSecondary" component="p">
Japanese: {poke.name.japanese} Chinese: {poke.name.chinese} French: {poke.name.french}
</Typography>
</CardContent>
<CardActions disableSpacing>
<IconButton
className={clsx(classes.expand, {
[classes.expandOpen]: expanded,
})}
onClick={handleExpandClick}
aria-expanded={expanded}
aria-label="show more"
>
<ExpandMoreIcon />
</IconButton>
</CardActions>
<Collapse in={expanded} timeout="auto" unmountOnExit>
<CardContent>
<Typography paragraph>Description</Typography>
<Typography paragraph>
Attack: {poke.base.Attack}
Defense: {poke.base.Defense}
Speed: {poke.base.Speed}
</Typography>
</CardContent>
</Collapse>
</Card>
</div>
))}
</div>
);
};
export default PokeDetail;
우선 JSX의 뷰 (HTML)에서 논리 (JS 코드)를 분리하여 코드를 더 깔끔하게 만들 것을 제안합니다.
id로 단일 poke를 표시하고 싶으므로 필터 대신 find를 사용하는 것이 좋습니다.
하나 더. "id"상수는 문자열입니다. 숫자와 함께 엄격한 유형 검사 (===)를 사용하고 있으며 이는 false를 반환합니다.
const foundPoke = pokemon.find(poke => poke.id === Number(id));
if (!foundPoke) {
return <div>Not found!</div>
}
return (
<div>
{poke.name}
</div>
);
또한 "포켓몬"소품이 개체 배열을 반환하지 않는다고 가정합니다. console.log (JSON.stringify (pokemon, null, 2))의 출력을 붙여 넣으라는 질문에 대한 의견을 추가했습니다.
[주제에서 약간 벗어남] 3 개월 동안 만 코딩한다고 하셨으므로 적절한 IDE를 사용하고 eslint와 예쁘게 구성하는 것이 좋습니다. 이 도구는 코드 스타일링에 도움이 될 것입니다 (들여 쓰기 문제가 있습니다)
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다