Next link 서버사이드렌더링 질문
382
작성한 질문수 10
안녕하세요! 강의를 응용해서 블로그를 만들어보고 있는데요!
<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
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를 이용했을 때 안되는 부분이라 어디가 문제인지 잘 모르겠습니다...
0
아 그리고 코드에서 저렇게 하면 showPosts가 안 생깁니다. useState(초깃값)이라서 초깃값이 빈 배열이었다가 Posts가 나중에 생기는 경우(next/link)에는 값이 업데이트가 안 됩니다.
애초에 처음부터 useSelector 안에서 처리해야 하는겁니다.
const { Posts } = useSelector((state) => (state.post.slice(startIndex, lastIndex)));
0
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를 이용해 불러온 데이터를 넣을 수는 없는건가요?
0
useState 안에 useSelector를 넣으시면 안 됩니다.
애초에 showPosts는 필요가 없습니다. startIndex와 lastIndex는 useState여야 하고요.
제가 강좌에서 너무 간단한 selector 예제만 보여드린 것 같은데요. useSelector는 리듀서 안의 데이터를 그대로 가져오는 게 아니라 거기서 모든 가공 처리를 해서 최종 결과물을 가져오는 겁니다. 즉, slice같은 작업도 전부 useSelector에서 해서 최종 결과물을 Posts로 받아오셔야 합니다.
0
0


첫번째 사진이 a tag를 이용했을 때 devtool이고,
두번째 사진이 next/link를 이용했을 때, devtool입니다.
둘다, store 의 Posts 에 데이터가 차는 걸로 보이긴 하지만, next/link를 썻을 때는, 화면에 데이터가 반영되지 않습니다.

넥스트 버젼 질문
0
77
2
로그인시 401 Unauthorized 오류가 뜹니다
0
89
1
무한 스크롤 중 스크롤 튐 현상
0
174
1
특정 페이지 접근을 막고 싶을 때
0
103
2
createGlobalStyle의 위치와 영향범위
0
96
2
인라인 스타일 리렌더링 관련
0
91
2
vsc 에서 npm init 설치시 오류
0
146
2
nextjs 15버전 사용 가능할까요?
0
158
1
화면 새로고침 문의
0
121
1
RTK에서 draft, state 차이가 있나요?
0
153
2
Next 14 사용해도 될까요?
0
452
1
next, node 버전 / 폴더 구조 질문 드립니다.
0
349
1
url 오류 질문있습니다
0
211
1
ssh xxxxx로 우분투에 들어가려니까 port 22: Connection timed out
0
372
1
sudo certbot --nginx 에러
0
1273
2
Minified React error 콘솔에러 (hydrate)
0
469
1
카카오 공유했을 때 이전에 작성했던 글이 나오는 버그
0
247
1
프론트서버 배포 후 EADDRINUSE에러 발생
0
326
1
npm run build 에러
0
518
1
front 서버 npm run build 중에 발생한 에러들
0
381
1
서버 실행하고 브라우저로 들어갔을때 404에러
0
337
2
css 서버사이드 랜더링이 적용되지 않아서 문의 드립니다.
0
287
1
팔로워 3명씩 불러오고 데이터 합쳐주는걸로 바꾸고 서버요청을 무한으로하고있습니다.
0
237
2
해시태그 검색에서 throttle에 관해 질문있습니다.
0
201
1






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