날아라김지원
article thumbnail

매우매우 고군분투했다.

 

console을 수도없이 찍어볼만큼 휴...!

 

하지만 요약해서 기록해두자

 

아래코드는 useEffect로 불러온 axios코드 부분이다.

 

let [array,setArray] = useState([])
........


return <>
......
.then((result)=>{console.log('요청성공')
    console.log(result)
    setArray(result.data)
......
{
  array.length ===0
  ?null
  :(
    array.map(function(a,index){
      return (
        <ResultBox key = {index} name={a.name} brand={a.brand}></ResultBox>
        // <p>{index} {a.name}</p>
        // 아니 배열+1개까지뜨다가지금은 왜 되냐..?
      )
    })
  )
}

........

</>

 

- 여러가지 시도를 해봤다. 그렇게 해본결과 알게된 특이사항 -

1.useEffect단에서 받아온 성공 결과 result, result.data를 useState에 저장해도

console을 찍으면 빈 배열로 나온다. 하지만 return구문, 렌더링 페이지에서는 무리 없이 사용할 수있음

아래와 같은 로직이다

1)상단에 선언한 useState

 

2)useEffect의 axios성공요청단에서 result.data를저장한다.

 

3)그리고 이곳에서 바로 state값을 console로찍으면 빈배열로나온다

 

4)하지만 return구문에서 3항연산자를 이용하면 정상적으로 출력된다.

-> 여기서문제, 삼항 연산자를 이용하지않고 바로 출력하면 출력이 되지않는다.

처음의 array의 빈값으로 저장된 useState([])상태를 보고 오류페이지를 출력한다.

하지만 삼항연산자로 조건을주고 값이 있을때 map반복문을 돌리게 했더니 정상적으로

출력되는 모습을 볼 수 있었다.

 

5)axios로 받아온 json값을 배열에 더 쉽고 편하게 넣는법..?

...구문을 사용하는것이다. 예를들어

그냥 빈 배열을 선언하고 push해주는것이아니라

let arr = []

arr.push(...result.data)

이런식으로 넣어주면 

위와같은 사진에서 겉 []껍데기 한번을 벗겨서 넣을 수 있다.

그래서 좀더 편하게 배열을 사용할 수 있게됨

 

아래는 소스코드 전문이다. 아래처럼하면 전체 리스트가 제대로 쭉 출력이 되긴하지만

 

10개건 100개건 200개건 한페이지에 나온다는게 단점이다, 그래서 페이지네이션을 사용해줄 필요가 있다.

 

억지로 for문을 사용하면 배열을 저장하는게 어려워 지지만, slice를 사용하면 매우 쉬워지고 간편? 해진다고 볼 수 있다.

 

axios로 받아오는 배열값을 사용하는것은 좀더 그때그때 궁리하고 확실히 정리해 봐야할거같다.

 

그래도 axios는 json값을 정리해주지만 fetch는..아니라고하니 감사하면서 사용하자

import type { NextPage } from 'next'
import { Container,Row,Col} from 'react-bootstrap';
import ResultBox from '../components/search/ResultBox'
import { useRouter } from "next/router";
import axios from 'axios'
import { useEffect, useState } from 'react';
import * as React from 'react';
import Typography from '@mui/material/Typography';
import Pagination from '@mui/material/Pagination';
import Stack from '@mui/material/Stack';

const Search: NextPage = () => {

  const {query} = useRouter()
  // let [q,Setq] = useState([query.ramenType,query.noodleType,query.ramenStyle])
  let [array,setArray] = useState([])
  let [pagenation,setPagenation] = useState([])
  let [pagetmp,setPagetmp] = useState([])

  const [page, setPage] = React.useState(1);
  const handleChange = (event, value) => {
    setPage(value);
  };

   useEffect(()=>{
     axios({
      method:'post',
      url:'http://j6c104.p.ssafy.io:8080/v1/ramen/category',
      data: {
        noodleType: query.noodleType,
        ramenStyle: query.ramenStyle,
        ramenType: query.ramenType,
      },
    })
    .then((result)=>{console.log('요청성공')
    console.log(result)
    // console.log(result.data)
    // console.log('------여기부터출력------')
    // let temp = []
    // temp.push(...result.data)
    setArray(result.data)
    // console.log(array)
    // console.log('여긴 안나오지만 밑에 삼항연산자에는 나옴')
    let arr = []
    let range = Math.ceil(result.data.length/5)-1
    let remain = result.data.length%5
    for(let i=0;i<range;i++){
      let arr2=[]
      arr2.push(...result.data.slice(5*i,5*i+5))
      arr.push(arr2)
    }
    let arr2=[]
    arr2.push(result.data.slice(5*range,5*range+remain))
    arr.push(...arr2)
    setPagenation(arr)
    // ...써봐..?
    // 
    console.log(arr)
    console.log('========')
    console.log(arr[0])
    // ...으로 벗기는것도 좋네
    console.log('========')
    console.log(arr[1])
    console.log(arr[2])
    console.log(arr[3])
    console.log(arr[3][0].name)
    console.log(arr[3].length)

    // console.log(page)
    setPagetmp(arr[1])
  })
    .catch((error)=>{console.log('요청실패')
    console.log(error)  
  })
  },[])

  return <>
  
  <Row>
    <Col xs={2} md={2}></Col>
    <Col xs={8} md={8}>
    <h1>카테고리결과</h1> 
    {
      pagenation.length
    }
    
    {/* {
  page.length ===0
  ?null
  :(
    page.map(function(a,index){
      return (
        <ResultBox key = {index} name={a[0].name} brand={a[0].brand}></ResultBox>
        // <p>{index} {a.name}</p>
        // 아니 배열+1개까지뜨다가지금은 왜 되냐..?
      )
    })
  )
} */}
{
  array.length ===0
  ?null
  :(
    array.map(function(a,index){
      return (
        <ResultBox key = {index} name={a.name} brand={a.brand}></ResultBox>
        // <p>{index} {a.name}</p>
        // 아니 배열+1개까지뜨다가지금은 왜 되냐..?
      )
    })
  )
}
<Stack spacing={2}>
{/* 여기가 page별로 다른거 보여주면될듯 */}

      <Typography>Page: {page}</Typography>
      <Pagination count={5} page={page} onChange={handleChange} />
    </Stack>
  
      {/* {
        name.map(function(n,i){
          return(
            <ResultBox key = {i} name={n} image={image[i]}></ResultBox>
          )
        })
      }   */}


 </Col>
    <Col xs={2} md={2}></Col>

  </Row>


  </>
   
  
}

export default Search

 

요약!

1)전체 리스트를 한페이지에 출력할것이다 ->이글을 참고해서 편하게 useState를 사용해 result.data를

저장하고 3항연산자를 사용한다음 map으로 전체리스트를 편하게 출력하면된다.

 

2)전체 리스트를 나눠서 페이지네이션으로 출력할것이다

->https://flykimjiwon.tistory.com/112

참고해서 사용하자

profile

날아라김지원

@flykimjiwon

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!