javascript - 服务器端渲染 - Redux 将状态传递给客户端
问题描述
我一直在用 React/Redux 试验 SSR,并按照Redux 网站上的教程进行操作。但是我没有成功通过窗口将我的状态从服务器传递到客户端。在客户端上,我的变量返回为未定义。我一直无法找到调试它的方法。
我也在使用打字稿进行开发,但构建到 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__;
总是以未定义的形式返回,因此我的组件永远不会因 hydra 上的不匹配结果而呈现在客户端上。
我可以尝试什么或可以采取哪些步骤来调试从服务器到客户端的切换?
解决方案
推荐阅读
- java - 是否可以将数据硬编码为 java 中的 Array 对象?
- python - 在 Pandas 中读取一个 excel 文件并合并未命名的列
- django - Django 单页应用程序中 HTML 页面的客户端和服务器端呈现
- swift - 从 iOS 收听 Kotlin 协程流程
- java - 如何在 Java 中的 JumpSearch 中输出左右块索引?
- date - 如何在 unix 中以 MM/DD/YYYY 格式打印日期?
- python - 在 Power BI 中使用 python 脚本操作 SQL 数据帧
- mysql - MySQL 内部多选的性能问题
- python - 使用python替换/删除文本文件中的附加注释
- angular - 实现异步/等待角度 7