[TIL] 01.20 read more

2020. 1. 20. 21:55TIL

객체형식의 데이터를 배열로 풀어준다.

  for(let i in articledata){
    for(let j=0; j < articledata[i][1].length; j++){
      articleList.push(articledata[i][1][j])
    }
  }

 

처음 랜더시켜줄 데이터를 잘라준다. 처음에 렌더가 되지 않는 문제를 해결해 주기 위해 기본 값을 설정해 주었다.
잘라준 데이터를 map을 돌려 articleComponent에 담아준다. 

  let articleSlice: any = articleList.slice(0, 12);
  let articleComponent: any = articleSlice.map((data: any) => {
    return (
      <Col key={data["title"]} span={6}>
        <Board data={data} handleTag={handleTag} />
        <div style={{ margin: "20px" }} />
      </Col>
    );
  });

 state 값으로 articleComponent를 지정해준다.

  const [articleArr, setarticleArr] = useState(articleComponent)

 

 자를 길이 값을 state로 지정해준다. 

  const [length, setlength] = useState({"Preitems":0, "items":12})

 

SliceArticle 함수가 실행이되면 articleSlice에 추후의 값이 추가되고
setarticleArr를 통해 state값을 변경 시켜 준다. 

  const SliceArticle = () => {
    let temp: [JSX.Element];
    temp = articleSlice.map((data: any) => {
      return (
        <Col key={data["title"]} span={6}>
          <Board data={data} handleTag={handleTag} />
          <div style={{ margin: "20px" }} />
        </Col>
      );
    });
    articleComponent = [...articleComponent, ...temp];
    setarticleArr(articleComponent);
  }

 

더 이상 자를 데이터가 없을땐 실행이 안되도록 조건문을 걸어주었다. 
Read More를 클릭하면 setlength를 통해 state 값이 변경 된다.  

  const handleReadMore = async() => {
    if (articleList.length > length.items) {
      setlength({ Preitems: length.items, items: length.items + 12 });
    }
  }

 

length의 값이 변화하면 articleSlice의 값이 재선언 되고 SliceArticle 함수가 실행이 된다.

추가로 프로필의 이미지를 넣어 주었다. 

  useEffect(() => {
    if (length.items !== 12) {
      articleSlice = articleList.slice(length.Preitems, length.items);
      SliceArticle();
    }
  }, [length]);

 

'TIL' 카테고리의 다른 글

[01.27] misinterpriter 배포  (0) 2020.01.27
[01.22] UI 수정  (0) 2020.01.22
[TIL] 01.19  (0) 2020.01.19
[TIL] 01.15  (0) 2020.01.15
[TIL] 01.14  (0) 2020.01.14