ReactJS 서버 측 렌더링 대 클라이언트 측 렌더링
방금 ReactJS를 연구하기 시작했는데 이것이 페이지를 렌더링하는 두 가지 방법 인 서버 측과 클라이언트 측을 제공한다는 것을 발견했습니다. 하지만 함께 사용하는 방법을 이해할 수 없습니다. 응용 프로그램을 빌드하는 두 가지 방법입니까, 아니면 함께 사용할 수 있습니까?
함께 사용할 수 있다면 어떻게해야하나요? 서버 측과 클라이언트 측에서 동일한 요소를 복제해야합니까? 또는 이미 미리 렌더링 된 서버 측에 연결하지 않고 서버에 애플리케이션의 정적 부분을 구축하고 클라이언트 측에 동적 부분을 구축 할 수 있습니까?
주어진 웹 사이트 / 웹 응용 프로그램에 대해 클라이언트 측 , 서버 측 또는 둘 다를 사용할 수 있습니다 .
고객 입장에서
여기에서 브라우저에서 ReactJS를 완전히 실행하고 있습니다. 이것은 가장 간단한 설정이며 대부분의 예제 ( http://reactjs.org에 있는 예제 포함)를 포함합니다 . 서버에서 렌더링 한 초기 HTML은 자리 표시 자이며 모든 스크립트가로드되면 전체 UI가 브라우저에서 렌더링됩니다.
서버 측
여기서 ReactJS를 서버 측 템플릿 엔진 (예 : jade, 핸들 바 등)으로 생각하십시오. 서버에서 렌더링 한 HTML에는 UI가 있어야하며 스크립트가로드 될 때까지 기다리지 않습니다. 귀하의 페이지는 검색 엔진에서 색인을 생성 할 수 있습니다 (JavaScript를 실행하지 않는 경우).
UI가 서버에서 렌더링되기 때문에 이벤트 핸들러가 작동하지 않으며 상호 작용이 없습니다 (정적 페이지가 있음).
양자 모두
여기에서 초기 렌더링은 서버에 있습니다. 따라서 브라우저에서 수신 한 HTML에는 UI가 있어야합니다. 스크립트가로드되면 가상 DOM이 다시 한 번 다시 렌더링되어 구성 요소의 이벤트 처리기를 설정합니다.
여기 props
에서 서버에서 렌더링하는 데 사용한 것과 동일한 가상 DOM (루트 ReactJS 구성 요소)을 다시 렌더링해야합니다. 그렇지 않으면 ReactJS는 서버 측과 클라이언트 측 가상 DOM이 일치하지 않는다고 불평합니다.
ReactJS는 re-render간에 가상 DOM을 비교하므로 실제 DOM은 변경되지 않습니다. 이벤트 핸들러 만 실제 DOM 요소에 바인딩됩니다.
이미지 출처 : Walmart Labs 엔지니어링 블로그
NB : SSR (서버 측 렌더링), CSR (클라이언트 측 렌더링).
The main difference being that with SSR, the servers response to the clients browser, includes the HTML of the page to be rendered. It is also important to note that although, with SSR, the page renders quicker. The page will not be ready for user interaction until JS files have been downloaded and the browser has executed React.
One downside is that the SSR TTFB (Time to First Byte) can be slightly longer. Understandably so, because the server takes some time creating the HTML document, which in turn increases the servers response size.
I was actually wondering the same researching quite a bit and while the answer you are looking for was given in the comments but I feel it should be more prominent hence I'm writing this post (which I will update once I can come up with a better way as I find the solution architecturally at least questionable).
You would need to write your components with both ways in mind thus basically putting if
switches everywhere to determine whether you are on the client or the server and then do either as DB query (or whatever appropriate on the server) or a REST call (on the client). Then you would have to write endpoints which generate your data and expose it to the client and there you go.
Again, happy to learn about a cleaner solution.
Is it 2 separate ways to build the application, or can they be used together?
They can be used together.
If we can use it together, how to do it - do we need to duplicate the same elements on the server side and client side? Or, can we just build the static parts of our application on the server, and the dynamic parts on the client side, without any connection to the server side that was already pre-rendered?
It's better to have the same layout being rendered to avoid reflow and repaint operations, less flicker / blinks, your page will be smoother. However, it's not a limitation. You could very well cache the SSR html (something Electrode does to cut down response time) / send a static html which gets overwritten by the CSR (client side render).
If you're just starting with SSR, I would recommend start simple, SSR can get very complex very quickly. To build html on the server means losing access to objects like window, document (you have these on the client), losing ability to incorporate async operations (out of the box), and generally lots of code edits to get your code SSR compatible (since you'll have to use webpack to pack your bundle.js). Things like CSS imports, require vs import suddenly start biting you (this is not the case in default React app without webpack).
The general pattern of SSR looks like this. An Express server serving requests:
const app = Express();
const port = 8092;
// This is fired every time the server side receives a request
app.use(handleRender);
function handleRender(req, res) {
const fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
console.log('fullUrl: ', fullUrl);
console.log('req.url: ', req.url);
// Create a new Redux store instance
const store = createStore(reducerFn);
const urlToRender = req.url;
// Render the component to a string
const html = renderToString(
<Provider store={store}>
<StaticRouter location={urlToRender} context={{}}>
{routes}
</StaticRouter>
</Provider>
);
const helmet = Helmet.renderStatic();
// Grab the initial state from our Redux store
const preloadedState = store.getState();
// Send the rendered page back to the client
res.send(renderFullPage(helmet, html, preloadedState));
}
My suggestion to folks starting out with SSR would be to serve out static html. You can get the static html by running the CSR SPA app:
document.getElementById('root').innerHTML
Don't forget, the only reasons to use SSR should be:
- SEO
- Faster loads (I would discount this)
해킹 : https://medium.com/@gagan_goku/react-and-server-side-rendering-ssr-444d8c48abfc
서버 측 렌더링은 처음에 서버에서 페이지를 렌더링하는 방법과 완전히 렌더링 된 페이지가 클라이언트로 다시 전송되는 방법입니다.
이 링크에서 더 자세한 정보를 얻을 수 있습니다. 여기를 클릭하세요
참고 URL : https://stackoverflow.com/questions/27290354/reactjs-server-side-rendering-vs-client-side-rendering
'development' 카테고리의 다른 글
setRetainInstance (true) 추가 이해 (0) | 2020.08.16 |
---|---|
Java에는 C #의 ref 및 out 키워드와 같은 것이 있습니까? (0) | 2020.08.16 |
C ++ 클래스에서 가상 메서드를 사용할 때의 성능 비용은 얼마입니까? (0) | 2020.08.16 |
Faye 대 Socket.IO (및 Juggernaut) (0) | 2020.08.16 |
C #에 CSV 리더 / 라이터 라이브러리가 있습니까? (0) | 2020.08.16 |