• 카테고리

    질문 & 답변
  • 세부 분야

    풀스택

  • 해결 여부

    미해결

Next link 서버사이드렌더링 질문

21.10.19 19:01 작성 조회수 199

0

안녕하세요! 강의를 응용해서 블로그를 만들어보고 있는데요!

<a href="/">Home</a>
<Link href="/" ><a>Home<a/></Link>

 

a태그를 이용해 이동 할 경우, 아래 getServerSideProps가 잘 작동하여, 데이터가 채워지는데,

Link를 이용해 이동 할 경우 데이터가 채워지지 않습니다.

export const getServerSideProps = wrapper.getServerSideProps(async (context) => {
  const cookie = context.req ? context.req.headers.cookie : '';
  axios.defaults.headers.Cookie = '';
  if (context.req && cookie) {
    axios.defaults.headers.Cookie = cookie;
  }
  context.store.dispatch({
    type: LOAD_MY_INFO_REQUEST,
  })
  context.store.dispatch({
    type: LOAD_POSTS_REQUEST,
  });
  context.store.dispatch(END);
  await context.store.sagaTask.toPromise();
});

새로고침이 되지 않으면 데이터가 채워지지 않는 것 같은데,

몇일 간 관련 자료를 찾아보아도 이런 경우가 없는 것 같아 질문드립니다..

 

답변 3

·

답변을 작성해보세요.

0

neostgeart님의 프로필

neostgeart

질문자

2021.10.20

  const { Posts } = useSelector((state) => (state.post));
  console.log("Posts"  + Posts);
  const [current,setCurrent] = useState(1);
  let startIndex = 0; 
  let lastIndex = 11;
  const [showPosts, setShowPosts] = useState(Posts.slice(startIndex,lastIndex));
  const onChange = useCallback((page) => {
    setCurrent(page);
    startIndex = (page-1) * 11;
    lastIndex = startIndex + 11;
    setShowPosts(Posts.slice(startIndex,lastIndex));
  },[current,showPosts]);
  console.log("showPosts : " + showPosts);

return (
    <AppLayout>
      <ListComponent Posts = {showPosts}/>
      <div style = {{marginBottom : "15px"}}></div>
      <Pagination style = {{textAlign : "center", marginTop : "20px", marginBottom : "15px"}} current={current} onChange={onChange} total={Posts.length-1} />
    </AppLayout>
  );

pagination을 위해 작성한 코드입니다.

console로 찍어보니 서버사이드렌더링 이후 Posts에는 데이터가 들어있는데, showPosts에는 데이터가 없어 데이터가 화면에 표시되지 않는 것 같습니다!

a tag를 이용했을 때는 잘되는데, next/link를 이용했을 때 안되는 부분이라 어디가 문제인지 잘 모르겠습니다...

데브툴에서 action 탭 말고 state 탭에 Posts가 차 있어야 실제로 차있는 것입니다. state 탭도 확인해보세요.

아 그리고 코드에서 저렇게 하면 showPosts가 안 생깁니다. useState(초깃값)이라서 초깃값이 빈 배열이었다가 Posts가 나중에 생기는 경우(next/link)에는 값이 업데이트가 안 됩니다.

애초에 처음부터 useSelector 안에서 처리해야 하는겁니다.

const { Posts } = useSelector((state) => (state.post.slice(startIndex, lastIndex)));
neostgeart님의 프로필

neostgeart

질문자

2021.10.20

 

let startIndex = 0; 
  let lastIndex = 11;
  const { Posts }  = useSelector((state) => (state.post));
  console.log("Posts");
  console.log(Posts);
  const [current,setCurrent] = useState(1);
  
  const [showPosts, setShowPosts] = useState(useSelector((state)=>(state.post.Posts.slice(startIndex,lastIndex))));
  const onChange = useCallback((page) => {
    setCurrent(page);
    startIndex = (page-1) * 11;
    lastIndex = startIndex + 11;
    setShowPosts(Posts.slice(startIndex,lastIndex));
  },[current,showPosts]);
  console.log("showPosts : " + showPosts);


  return (
    <AppLayout>
      <ListComponent Posts = {showPosts}/>
      <div style = {{marginBottom : "15px"}}></div>
      <Pagination style = {{textAlign : "center", marginTop : "20px", marginBottom : "15px"}} current={current} onChange={onChange} total={Posts.length-1} />
    </AppLayout>
  );

 

code를 위와같이 수정했더니 잘 되는 것 같습니다!

 

그럼 혹시, useState의 초깃값에는 다른 hooks를 이용해 불러온 데이터를 넣을 수는 없는건가요?

useState 안에 useSelector를 넣으시면 안 됩니다.

애초에 showPosts는 필요가 없습니다. startIndex와 lastIndex는 useState여야 하고요.

제가 강좌에서 너무 간단한 selector 예제만 보여드린 것 같은데요. useSelector는 리듀서 안의 데이터를 그대로 가져오는 게 아니라 거기서 모든 가공 처리를 해서 최종 결과물을 가져오는 겁니다. 즉, slice같은 작업도 전부 useSelector에서 해서 최종 결과물을 Posts로 받아오셔야 합니다.

const onChange = useCallback(() => {
  setLastIndex(...);
  setStartIndex(...);
}, []);

0

neostgeart님의 프로필

neostgeart

질문자

2021.10.20

첫번째 사진이 a tag를 이용했을 때 devtool이고,

두번째 사진이 next/link를 이용했을 때, devtool입니다.

둘다, store 의 Posts 에 데이터가 차는 걸로 보이긴 하지만, next/link를 썻을 때는, 화면에 데이터가 반영되지 않습니다.

0

redux-devtools로 보면 어떻게 뜨나요? 액션들이 존재하나요?