반응형
드디어다.. 서버사이드 렌더링... 알바하느라 못적은 글 시작한다.
01. ssr
일단 reducer중 rootReducer 부터 고친다.
기존
import { combineReducers } from "redux";
import UserReducer from "./user";
import PostReducer from "./post";
const rootReducer = combineReducers({
user: UserReducer.reducer,
post: PostReducer.reducer,
});
export default rootReducer;
변화후
export interface IRootReducer {
user: UserInitialState;
post:PostInitialState;
}
// rootReducer 확장
const rootReducer = (state: IRootReducer, action: AnyAction) => {
switch (action.type) {
default: {
const combineReducer = combineReducers({
user: UserReducer.reducer,
post: PostReducer.reducer,
});
return combineReducer(state, action);
}
}
};
뭐가 달라진거야 라고 하면 HYDRATE을 하기 위해 확장한거 이외는 없다.
현재 결과는 같다.
이거 에서 나는 HYDRATE을 추가 한다.
여기서 잠깐 HYDRATE란?
서버 사이드 렌더링(SSR) 시 클라이언트의 초기 상태를 서버에서 전달받아 Redux 스토어에 주입하는 데 사용된다.
고로 해서 이렇게 바뀜
const rootReducer = (state: IRootReducer, action: AnyAction) => {
switch (action.type) {
case HYDRATE:
console.log("HYDRATE", HYDRATE)
return action.payload
default: {
const combineReducer = combineReducers({
user: UserReducer.reducer,
post: PostReducer.reducer,
});
return combineReducer(state, action);
}
}
};
그리고 ssr을 해야하는페이지마다 작성을 해야하는데
export const getServerSideProps:GetServerSideProps =
wrapper.getServerSideProps((store) => async({ req })=>{
// 리퀘스트에서 가만히 있는게 아니라 성공으로 가게 하기 위해서.
const cookie = req ? req.headers.cookie: "";
axios.defaults.headers.Cookie = ""
if(req && cookie){
axios.defaults.headers.Cookie = cookie;
}
await store.dispatch(posts(1));
return {
props:{},
}
})
dispatch를 제외한 나머지를 작성안하면 리퀘스트상태에서 멈추고 cookie관련되서 작성을 하면 이게 정보가 불러와진다.
그 이유라고 하면 req.headers에 요청을 보낸다 라는 의미 이기 때문이다 결론은 정보줄꺼야? 에서 정보 내놔로 변경되는 의미 이다.
이거 사용하면 ssr은 끝
여기서 중요점 일단 다른곳에서 퍼온건데 이거는 외워두는게 좋지 않을까 생각 된다.
getServerSideProps :
- 서버 사이드 렌더링(SSR)에 사용됩니다.
- 매 요청마다 데이터를 서버에서 가져옵니다.
- 요청 시점에 동적으로 데이터를 가져와 화면에 표시하거나 처리할 수 있습니다.
- 매 요청마다 데이터를 가져오기 때문에 항상 최신 데이터를 제공합니다.
- 주로 사용자에 따라 다른 데이터가 필요하거나, 데이터가 자주 업데이트되는 경우에 적합합니다.
getStaticProps :
- 정적 생성(Static Generation)에 사용됩니다.
- 빌드 시점에 데이터를 미리 가져와서 정적인 HTML 파일로 생성합니다.
- 미리 생성된 정적 파일을 서빙하므로 서버 부하가 적고 응답 속도가 빠릅니다.
- 데이터가 변경되면 재빌드해야 최신 데이터를 반영할 수 있습니다.
- 주로 변경이 적고, 공통적으로 사용되는 데이터에 적합합니다.
02. css 서버사이드 랜더링
_document
import type { DocumentContext, DocumentInitialProps } from "next/document";
import Document from "next/document";
import { ServerStyleSheet } from "styled-components";
export default class MyDocument extends Document {
static async getInitialProps(
ctx: DocumentContext
): Promise<DocumentInitialProps> {
const sheet = new ServerStyleSheet();
const originalRenderPage = ctx.renderPage;
try {
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) =>
sheet.collectStyles(<App {...props} />),
});
const initialProps = await Document.getInitialProps(ctx);
return {
...initialProps,
styles: [initialProps.styles, sheet.getStyleElement()],
};
} finally {
sheet.seal();
}
}
}
.babelrc
{
"presets": ["next/babel"],
"plugins": [
[
"styled-components",
{
"ssr": true,
"displayName": true,
"preprocess": true
}
]
]
}
외우지 마라 그냥 복붙해... 안외울수 잇음 안외우는게 최고임....
반응형
'nodebird' 카테고리의 다른 글
getStaticPaths (0) | 2024.03.06 |
---|---|
node 쓰면서 알아야할 것들 (0) | 2024.03.05 |
이미지 올려보자잇 (1) | 2024.02.08 |
게시물을 불러오장 (2) | 2024.02.07 |
패스포트로그인 (0) | 2024.01.29 |