首页 > 解决方案 > 服务器端渲染 - 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 上的不匹配结果而呈现在客户端上。

我可以尝试什么或可以采取哪些步骤来调试从服务器到客户端的切换?

标签: javascriptreactjstypescriptredux

解决方案


推荐阅读