서버 렌더링 react-router v4 패스스루(404인 경우)
react-router v3에서는 서버측 렌더링이 현재 URL과 일치하지 않는 경우를 알 수 있었다.이것으로 나는 그 요청을 내 손에 넘길 수 있었다.express.static
렌더링된 앱을 보내는 대신 미들웨어.
react-router v4에서는
const htmlData = renderToString(
<StaticRouter
location={req.url}
context={context}
>
<App/>
</StaticRouter>
);
서버 측에서 렌더링할 수 있도록.그러나 모든 것을 자동으로 다음으로 자동 리디렉션/
왜 이런 행동이 존재하는가?우리가 예상한 대로 묵묵히 실패하는 오류를 범할 수는 없을까?
아무 것도 일치하지 않는다는 것을 어떻게 알 수 있었기에 내가 전화를 걸 수 있었다.next()
다른 급행열차의 노선이 그 일을 맡긴다고?
다음은 내가 사용하고자 하는 모든 기능이다.
app.get('*', (req, res, next) => {
const context = {};
const htmlData = renderToString(
<StaticRouter
location={req.url}
context={context}
>
<App/>
</StaticRouter>
);
console.log(JSON.stringify(context, null, 4)); // empty object
if (context.url) { // <------------------------ Doesn't work (taken from example and thought it would contain the unmatched url)
winston.info(`Passing ${req.url} along`);
next(); // <--------------- Never called even if no route matches.
} else {
res.send(pageContent.replace('<div id="main"></div>',
`<div id="main">${htmlData}</div>`));
}
});
이걸 토대로 해서 하려고 했는데.// somewhere else
너무 정확해서 전혀 이해할 수가 없었어.
도움이 될 경우를 대비해서 마지막 시도를 해보겠다.바로 이겁니다.Router.jsx
파일:내 모든 것을 정의할 계획Route
s
import React from 'react';
import PropTypes from 'prop-types';
import {
BrowserRouter,
Route,
} from 'react-router-dom';
import App from './components/App.jsx';
export const Status = ({ code, children }) => (
<Route render={({ staticContext }) => {
if (staticContext) {
staticContext.status = code;
}
return children;
}}/>
);
Status.propTypes = {
code : PropTypes.number.isRequired,
children : PropTypes.node.isRequired,
};
export const NotFound = () => (
<Status code={404}>
<div>
<h1>Sorry, can’t find that.</h1>
</div>
</Status>
);
class Router extends React.Component {
render() {
return (
<BrowserRouter>
<div>
<Route exact path="/" component={App}/>
<Route component={NotFound}/>
</div>
</BrowserRouter>
);
}
}
export default Router;
(이것은 그 이후로 전혀 말이 되지 않는다는 것을 알고 있다.StaticRouter
직접 사용하다App
개의치 않고Router.jsx
하지만 나는 없다.Route
속으로는 전혀App
그래서 난 어떻게 해야 할지 잘 모르겠어
전혀 사용하지 않는 Route.jsx가 아닌 App.jsx 파일에 NotFoundPage 구성 요소 경로 논리를 넣으십시오.
<Switch>
<Route exact path="/" component={AppRootComponent}/>
<Route component={NotFound}/>
</Switch>
이 외에도, 이 자습서 코드는 리액션 라우터 v4를 사용한 서버 측 렌더링에 대한 훌륭한 참조 자료다.
참조URL: https://stackoverflow.com/questions/44475946/server-rendering-react-router-v4-passthrough-if-404
'Programing' 카테고리의 다른 글
OS X에서 Python의 기본 버전을 3.x로 설정하는 방법 (0) | 2022.03.12 |
---|---|
TypeError: Python3에서 파일에 쓸 때 'str'이 아니라 바이트와 같은 개체가 필요함 (0) | 2022.03.12 |
기본 외부 스타일시트 반응 (0) | 2022.03.12 |
Vue Js - v-for X time(범위 내)을 통한 루프 (0) | 2022.03.12 |
동일한 페이지에 여러 번 표시된 Vuejs 구성 요소를 동기화할 수 있는가? (0) | 2022.03.12 |