Reactjs 使用从API调用的数据进行服务器端渲染
我使用react redux+thunk+redial在服务器端生成HTML。我想使用来自另一台服务器的用户数据生成元标记。 在我的服务器中:Reactjs 使用从API调用的数据进行服务器端渲染,reactjs,redux,react-redux,redux-thunk,Reactjs,Redux,React Redux,Redux Thunk,我使用react redux+thunk+redial在服务器端生成HTML。我想使用来自另一台服务器的用户数据生成元标记。 在我的服务器中: import { trigger } from 'redial'; trigger('fetch', components, locals) .then(() => { const state = getState(); var html = ReactDOMServer.renderToStri
import { trigger } from 'redial';
trigger('fetch', components, locals)
.then(() => {
const state = getState();
var html = ReactDOMServer.renderToString (
<Provider store={store} key="provider">
<ReactRouter.RouterContext {...renderProps} />
</Provider>
);
let head = Helmet.rewind();
response.send(`<!DOCTYPE html>
<head>
<meta charSet="UTF-8"></meta>
<meta httpEquiv="X-UA-Compatible" content="IE=edge,chrome=1"></meta>
<meta name="viewport" content="width=device-width, initial-scale=1"></meta>
<link rel='stylesheet' href='/css/bootstrap.css'/>
${style? "<style>"+style+"</style>" : "<link rel='stylesheet' href='/css/app.css'/>"}
${head.title}
${head.meta}
${head.link}
${head.script}
</head>
<body>
<div id="app">${html}</div>
<script src='/javascript/bundle.js'></script>
${popUp}
</body>
</html>`);
在
render()
方法中调用dispatch是错误的做法,因为render方法应该是不可变的。使用redial
提供的挂钩包装组件,以解析数据API。参考中的示例用法。最后,在react服务器端渲染中对来自另一台服务器的数据进行了大量渲染后,我找到了最佳解决方案。
首先,你不需要重拨,这是多余的,至少对我来说是这样。所以我把它从我的来源中删除了。
然后,我搬家了
dispatch(
actions.theProfile(x,y,z)
)
我的路线
export default (store) => {
const requireApiCall= (nextState, replace, cb) => {
var state = store.getState();
return store.dispatch(actions.theProfile(x,y,z)).
then(()=>{
cb()
})
};
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="profile" component={Profile } onEnter={requireApiCall}>
</Route>
</Route>
}
导出默认值(存储)=>{
const requireApiCall=(下一状态、替换、cb)=>{
var state=store.getState();
return store.dispatch(actions.theProfile(x,y,z))。
然后(()=>{
cb()
})
};
}
调度将执行,路由将等待回调“cb()”,当我的API调用得到响应时,我的存储将使用收到的数据进行更新。然后action解析承诺,然后RequireAppall中的承诺解析并返回回调“cb()”。路由开始呈现组件,发送到客户端的应答将使用接收到的数据生成
我知道这有点复杂,但效果很好。我应该这样做,我在写了这个问题后注意到了,但我没有测试它。我明天会做,我希望它能解决问题。我做了,但问题仍然存在。它甚至没有采取行动。
dispatch(
actions.theProfile(x,y,z)
)
export default (store) => {
const requireApiCall= (nextState, replace, cb) => {
var state = store.getState();
return store.dispatch(actions.theProfile(x,y,z)).
then(()=>{
cb()
})
};
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="profile" component={Profile } onEnter={requireApiCall}>
</Route>
</Route>
}