我正在尝试使用异步调用使服务器渲染生效。我的问题是,在渲染之前数据没有被下载。
以下是我的代码(也可在github上查看:https://github.com/tomekbuszewski/server-rendering):
server.js
以下是我的代码(也可在github上查看:https://github.com/tomekbuszewski/server-rendering):
server.js
require('babel-register');
import express from 'express';
import path from 'path';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { Provider } from 'react-redux';
import { getState } from 'redux';
import { match, RouterContext } from 'react-router'
import routes from './app/routes';
import store from './app/store';
const app = express();
const port = 666;
app.get('/', (req, res) => {
match({ routes, location: req.url }, (error, redirectLocation, renderProps) => {
if (renderProps) {
console.log(renderProps.components);
res.send(renderToString(
<Provider store={store}>
<RouterContext {...renderProps} />
</Provider>
))
} else {
console.log('err')
}
});
});
app.use('/public', express.static(path.join(__dirname, 'public')));
app.use('/data', express.static(path.join(__dirname, 'data')));
app.listen(port);
console.log(`localhost:${port}`);
routes.js
import React from 'react';
import { Router, Route, browserHistory } from 'react-router';
import App from './Components/App';
const routes = (
<Router history={browserHistory}>
<Route path="/" component={App} />
</Router>
);
export default routes;
App组件有一个fetch函数:
const fetch = (dispatch) => {
const endpoint = '/data/index.json';
axios.get(endpoint).then((res) => {
Array.prototype.forEach.call(res.data, d => {
const payload = {
id: d.id,
title: d.title
};
dispatch({type: 'ADD_CONTENT', payload});
});
});
};
这个函数派发了“ADD_CONTENT”动作:
case 'ADD_CONTENT':
return { ...state, data: [...state.data, action.payload] };
所有工作在客户端都很好。
redux-connect
的信息,但我必须承认他们的示例非常令人困惑。我已经得到了服务器路径,但组件路径对我来说非常奇怪。我应该如何使用@asyncConnect
连接我的数据?我应该放弃我的reducers并仅使用reduxAsyncConnect
吗? - Tomek BuszewskicombineReducers(...)
调用中,只需包含来自redux-connect
的 reducer,而不会对其他 reducer 产生任何影响。我不知道它是否是强制性的,也许是为了跟踪预加载状态,我个人在我的布局中使用它来显示“加载中”消息,当客户端发生加载时,即在第一次 SSR 后的所有后续路由更改。 - PandaioloasyncConnect
? - Tomek Buszewski@connect
来自react-redux
库,它是我在使用 react 和 redux 的方法,不知道是否还有其他的方法?就像这个教程中所解释的那样:http://www.jchapron.com/2015/08/14/getting-started-with-redux/#3buildingtheui。你可以将它作为组件导出时的函数,而不是装饰器。(请参考 react-redux 文档,它们使用的是这种方式) - Pandaiolo