Я использую реагирующий маршрутизатор v4 с избыточностью для рендеринга некоторых данных на сервере, но я не могу установить состояние компонента на сервере. Вот мой код Ценим помощь
вот функция загрузки сервера на стороне сервера
loadOnServer({ store, location, routes }).then(() => {
const context = {};
const html = renderToString(
<Provider store={store}>
<StaticRouter location={location} context={context}>
<ReduxAsyncConnect routes={routes} />
</StaticRouter>
</Provider>
);
// handle redirects
if(context.url) {
req.header('Location', context.url)
return res.send(302)
}
// render the page, and send it to the client
res.send(renderLayout(html, '', store.getState(),ApiData , req.protocol + '://' + req.get('x-forwarded-host')));
// render the page, and send it to the client
// can't use until redux-connect works with loadable-components
// getLoadableState(html).then(pageScripts =>
// res.send(renderLayout(html, pageScripts.getScriptTag(), store.getState(), !!(req.user && req.user.isAdmin)))
// )
})
.catch(err => {
console.log(err);
res.status(500).end();
});
ApiData - это данные с сервера, которые необходимо настроить на сервере, чтобы компоненты выводили
Вот мой index.js
import React from 'react';
import { hydrate } from 'react-dom';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import { BrowserRouter, Route } from 'react-router-dom';
import { ReduxAsyncConnect } from 'redux-connect';
import createHistory from 'history/createBrowserHistory';
import { ConnectedRouter, routerMiddleware, push } from 'react-router-redux';
import routes from './routes';
import reducers from './reducers';
import App from './app';
const initialState = window.__INITIAL_STATE;
const history = createHistory();
const middleware = routerMiddleware(history);
const store = createStore(reducers, initialState, applyMiddleware(middleware));
hydrate(
<Provider store={store}>
<ConnectedRouter history={history}>
<ReduxAsyncConnect routes={routes}/>
</ConnectedRouter>
</Provider>,
document.getElementById('app')
);
Вот мои маршруты. Js
import React from 'react';
import App from './app';
import HomePage from './pages/HomePage';
const routes = [{
component: App,
routes: [
{
path : '/',
exact: true,
component: HomePage
}
]
}];
export default routes;
И вот мой App.js
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import renderRoutes from 'react-router-config/renderRoutes';
import routes from './routes';
import {isBrowser,isServer} from './util/environmentDetection'
class App extends Component {
constructor(props) {
super(props);
if(isServer) {
} else if(isBrowser && !this.state) {
this.state = window.__DATA;
delete window.__DATA;
}
}
render() {
return (
<div>
<Link to={'/'}>
{'Home'}
</Link>
{renderRoutes(routes[0].routes, { initialData : this.state })}
</div>
);
}
}
export default App;