Я создаю изоморфный магазин с реакцией и nodejs. Моя проблема заключается в том, как заполнить мои компоненты исходными данными на сервере SERVER SIDE. Я знаю, как заполнить компоненты моей домашней страницы исходными данными, я получаю данные на маршруте «/» и передаю их своим компонентам в качестве реквизита. Но как насчет других маршрутов? Я могу определить несколько маршрутов на стороне сервера, но мой сайт больше не SPA. Как я могу получить bennefits отклика на стороне клиента на стороне клиента и инициировать данные на стороне сервера?реакция изоморфна и исходные данные
ответ
redux может сэкономить вам время на такое. Или вы можете рассчитать состояние на сервере и заполнить его как json в репозитории вашего приложения store store thourgh.
React router is isomorphic легко, но вы должны передать свое состояние в любом случае.
Вот мой пример index.jsx с маршрутизатором реагируют без перевождь:
"use strict";
import React from 'react';
import { render } from 'react-dom';
import { match, Router, browserHistory } from 'react-router';
const injectTapEventPlugin = require('react-tap-event-plugin');
injectTapEventPlugin();
//for dev tools
window.React = React;
const routes = require('./Routes.jsx');
const history = browserHistory;
match({history, routes}, (error, redirectLocation, renderProps) => {
render(<Router {...renderProps} />, document.getElementById('app'));
})
и Routes.jsx вы найдете что-то вроде:
"use strict";
const React = require('react');
import { Router, Route, Link, IndexRoute } from 'react-router'
const Layout = require("./components/Layout.jsx");
const Login = require("./components/Login.jsx");
const Home = require("./components/Home.jsx");
const NotFound = require("./components/NotFound.jsx");
const routes = (
<Route path="/" component={Layout}>
<IndexRoute component={Home}/>
<Route path="login" component={Login}/>
<Route path="*" component={NotFound}/>
</Route>
);
module.exports = routes;
Я использую следующий компонент на стороне сервера для SPA с реактивным маршрутизатором, проходящий в местоположении prop и исходный объект состояния в ReactDOMServer.renderToString()
исх: React-Router Server Rendering docs
import React, { Component } from 'react';
import { createStore, combineReducers } from 'redux';
import { Provider } from 'react-redux';
import reducers from '../reducers';
import routes from '../routes';
import { match, RoutingContext } from 'react-router';
export default class App extends Component {
constructor(props) {
super(props);
}
render() {
let reducer = combineReducers(reducers);
let store = createStore(reducer, this.props);
var component;
match({ routes, location: this.props.location }, function (error, redirectLocation, renderProps) {
if (error) {
component = <p>{error.message}</p>;
} else if (renderProps) {
component = <RoutingContext {...renderProps} />;
} else {
component = <p>404 not found</p>;
}
})
return (
<Provider store={store}>
{component}
</Provider>
)
}
}
Вот реальная жизнь изоморфными приложение https://github.com/WebbyLab/itsquiz-wall все эти вопросы уже решены.
демографические проблемы Данные охватывали здесь https://github.com/WebbyLab/itsquiz-wall/blob/master/server/app.js
А вот мой Блогпост о решении изоморфными вопросов - "The Pain and the Joy of creating isomorphic apps in ReactJS"