Как установить состояние на сервере для данных из API, используя реагировать на редукцию - PullRequest
0 голосов
/ 02 мая 2018

Я использую реагирующий маршрутизатор 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;

1 Ответ

0 голосов
/ 15 мая 2018

Вот как я получаю состояние запроса (машинопись). Тем не менее, я не уверен, как затем получить req.cookies из магазина из моих действий, которые необходимы для того, чтобы магазин был полностью заполнен. Возможно, я здесь что-то не так делаю.

<code>app.get('*', (req, res) => {
    const location = req.url;
    const memoryHistory = createMemoryHistory(req.originalUrl);
    const store = configureStore(memoryHistory);
    const history = syncHistoryWithStore(memoryHistory, store);

    match({history, routes, location},
        (error, redirectLocation, renderProps) => {
            if (error) {
                res.status(500).send(error.message);
            } else if (redirectLocation) {
                res.redirect(302, redirectLocation.pathname + redirectLocation.search);
            } else if (renderProps) {
                const asyncRenderData = {...renderProps, store, cookies: req.cookies};
                loadOnServer(asyncRenderData).then(() => {
                    const css = [];
                    const markup = ReactDOMServer.renderToString(
                        <WithStylesContext onInsertCss={(styles) => css.push(styles._getCss())}>
                            <Provider store={store} key="provider">
                                <ReduxAsyncConnect {...renderProps} />
                            </Provider>
                        </WithStylesContext>,
                    );
                    try {
                        res.status(200).send(renderHTML(markup, store, css));
                    } catch (err) {
                        res.status(500).send('<pre>' + err + '
'); } }). catch ((err) => { console.log («отправка 404», ошибка); res.status (404) .send (x404 (JSON.stringify (err || {}))); }); } еще { // /3789069/perenapravlenie-po-umolchaniy-dlya-oshibki-404 res.status (404) Пошлите (X404 (нуль)); } }); });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...