我一直在使用React / Redux进行SSR实验,并遵循Redux website上的教程。但是我无法通过窗口将状态从服务器传递到客户端,因此没有成功。在客户端上,我的变量返回未定义状态。我还没有找到一种调试方法。
我也在使用打字稿进行开发,但是正在使用JavaScript(不确定是否会给我带来麻烦)
服务器代码
app.get("/reactComponent", function (req, res) {
var hardCodedState = { person: [{ firstName: "John", lastName: "Doe" }]};
const store = createStore(appReducer, hardCodedState);
const body = renderToString(
<Provider store={store}>
<Data />
</Provider>
);
const preloadedState = store.getState();
res.send(renderHTML(body, preloadedState));
});
function renderHTML(html, preloadedState) {
return `<!doctype html>
<html>
<head>
<title>Redux Universal Example</title>
</head>
<body>
<div id="root">${html}</div>
<script>
window.__REDUX_STATE__ = ${JSON.stringify(preloadedState).replace(/</g,'\\u003c')}
</script>
<script src="/static/bundle.js"></script>
</body>
</html>`
}
客户端
public componentDidMount(){
axios.get("http://localhost/reactComponent").then(response => {
const preloadedState = (window as any).__REDUX_STATE__;
// delete (window as any).__REDUX_STATE__;
const store = createStore(appReducer,preloadedState);
hydrate(<Provider store={store}><Data /></Provider>, document.getElementById("content"));
}).catch(error =>{
console.log("error",error);
});
}
const preloadedState = (window as any).__REDUX_STATE__;
总是以未定义的形式返回,因此我的组件永远不会因水合物的不匹配结果在客户端上呈现。
我能尝试尝试采取什么措施或调试从服务器到客户端的切换吗?