В настоящее время я работаю над новым проектом, поэтому я решил реализовать React, но с рендерингом на стороне сервера. Я использую express в качестве маршрутизатора между страницами, поэтому при доступе к домашней странице точка входа выглядит примерно так:
const router = require('express').Router();
const { render, fetchUsers } = require('./controller');
router.use('/', fetchUsers, render);
module.exports = router;
Так что, когда вы заходите на домашнюю страницу, все пользователи и затем он отрендерит компонент, для рендеринга компонента я делаю следующее:
const render = (req, res) => {
const extraProps = {
users: res.locals.users.data,
}
return renderView(View, extraProps)(req, res);
}
метод fetchUsers устанавливает res.locals.users с ответом API. Мой renderView делает что-то вроде этого:
const renderView = (Component, props = {}) => (req, res) => {
const content = renderToString(
<LayoutWrapper state={props}>
<Component {...props} />
</LayoutWrapper>
);
res.send(content);
};
Мой LayoutWrapper является компонентом React, который заменяет шаблон html:
const React = require('React');
const serialize = require('serialize-javascript');
const LayoutWrapper = ({ children, state }) => (
<html>
<head></head>
<body>
<div id={'app-root'}>
{children}
</div>
</body>
<script>
{`window.INITIAL_STATE = ${serialize(state, { isJSON: true })}`}
</script>
<script src={`home.js`} />
</html>
)
module.exports = LayoutWrapper;
Сценарий, который устанавливает window.INITAL_STATE = props; используется на стороне клиента, чтобы получить реквизиты, которые были выбраны. Но проблема в том, как renderToString обрабатывает компонент. Вывод console.log следующий:
<html data-reactroot="">
<head></head>
<body>
<div id="app-root">
<div>I'm the Home component</div><button>Press me!</button>
<ul>
<li>Leanne Graham</li>
<li>Ervin Howell</li>
<li>Clementine Bauch</li>
<li>Patricia Lebsack</li>
<li>Chelsey Dietrich</li>
</ul>
</div>
</body>
<script>
window.INITIAL_STATE = { & quot;users & quot;: [{ & quot;id & quot;: 1,
& quot;name & quot;: & quot;Leanne Graham & quot;
}, { & quot;id & quot;: 2,
& quot;name & quot;: & quot;Ervin Howell & quot;
}, { & quot;id & quot;: 3,
& quot;name & quot;: & quot;Clementine Bauch & quot;
}, { & quot;id & quot;: 4,
& quot;name & quot;: & quot;Patricia
Lebsack & quot;
}, { & quot;id & quot;: 5,
& quot;name & quot;: & quot;Chelsey Dietrich & quot;
}]
}
</script>
<script src="home.js"></script>
</html>
Есть ли способ сделать это, не объявляя шаблон html как простую строку, и вместо этого имея компонент Wrapper, который устанавливает html структура кода?