Cannot read properties of undefined (reading 'map')
TypeError: Cannot read properties of undefined (reading 'map')

첫 턴에 데이터가 안 들어왔을 때에도 렌더링이 실행된다. 그래서 데이터가 undefined라 생기는 문제인데 다른 블로그를 보니
return (
{currentItems.map((item, index) => (
<GridBox key={index} item={item} gridArea={`gridBox${index % 10 + 1}`} />
))}
)
currentItems.map 앞에 currentItems && 을 넣어주면 된다는거였다. 여기서의 핵심은 먼저 and로 연결되어 있기에 currentItems이 존재하면 괄호 안을 실행한다는건데 그러면 아래처럼 위 아래만 뜨고 아무런 결과가 뜨지 않았다.

return 안에서 currentItems를 data.item으로 호출했을 때는 잘 떴다. 왜 떴을까 생각해보니 if (!data) { return null; } 이 부분이 있어서 그랬던 것 같다.
if (!(data && currentItems)) { return null; }
그래서 이렇게 해보았다.

그랬더니 이렇게 잠깐 떴다 사라졌다. 이건 또 왜? openapi는 잘 불러와지는데.
위의 if문에 더해서 currentItems.map 앞에 currentItems && 까지 추가시켜주니 작동했다,, 아까는 안 됐던 것 같은데 뭐지.

관련 전체코드는 더보기에
더보기
전체코드
const SearchResultPage = () => {
const [currentPage, setcurrentPage] = useState(1)
const [currentArray, setCurrentArray] = useState(0);
const [totalPage, setTotalPage] = useState([]);
const [slicePages, setSlicePages] = useState([]);
const [itemsPerPage, setItemsPerPage] = useState([]);
const [currentItems, setCurrentItems] = useState([]);
const pagePerLimit = 10
const pageArrayLimit = 5
const maxResults = 50
// 책 데이터 db에 저장
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
const searchResultFunc = async () => {
setLoading(true);
try {
const result = await axios.get(`ttb/api/ItemSearch.aspx?ttbkey=${process.env.REACT_APP_TTBKEY}&Query=모순&QueryType=Title&MaxResults=${maxResults}&start=${currentArray + 1}&SearchTarget=Book&output=js&Version=20131101`);
console.log(result.data)
setData(result.data);
const newItemSlice = [];
for (let i = 0; i < maxResults; i += pagePerLimit) {
newItemSlice.push(result.data.item.slice(i, i + pagePerLimit));
}
setItemsPerPage(newItemSlice)
} catch (e) {
console.log(e);
}
setLoading(false);
}
useEffect(() => {
searchResultFunc();
}, [currentArray]);
if (!(data && currentItems)) {
return null;
}
return (
{currentItems && currentItems.map((item, index) => (
<GridBox key={index} item={item} gridArea={`gridBox${index % 10 + 1}`} />
))}
)
}
'웹 > React' 카테고리의 다른 글
[React] 흐르는 텍스트 시작 지점 설정 (0) | 2023.09.17 |
---|---|
[React] useEffect set state가 바로 적용 안 되는 현상 (0) | 2023.09.15 |
[React] 페이지 버튼 클릭 후 css 효과 유지하기(현재 페이지 표시) (0) | 2023.09.08 |
[React] 페이지네이션 페이지 이동 딜레이문제 (0) | 2023.09.07 |
[React] Warning: React does not recognize the `isActive` prop on a DOM element. (0) | 2023.09.04 |
댓글