gpt4 book ai didi

javascript - 使用 React/Redux,我如何动态预加载状态?

转载 作者:行者123 更新时间:2023-11-30 15:25:20 24 4
gpt4 key购买 nike

我很难用 React/Redux 预加载状态。

在将其标记为重复之前,我已经阅读了这些内容:

这是我的场景:

  • 我正在使用 Node + React + Redux。
  • 当我从服务器加载页面时,我从数据库加载 User 对象。我需要此 User 对象处于无需往返服务器的状态。
  • 因为 User 对象是动态的,所以我不能将它放在包中。
  • 没有使用服务器渲染。

我的问题:

最初如何将用户对象从服务器加载到我在客户端的存储中?

this answer ,丹阿布拉莫夫说:

On the client, you’d read it from a global variable, and create the client store instance with it. In other words you never have to manually create initialState—you’re supposed to grab it on the server with store.getState(), pass it to client, and create a store with it.

所以,我假设,通过全局变量,他的意思是这样的:

// Here, window._initialState.user is being sent to the client in a <script/> tag.
const store = createStore(reducers, { user: window._initialState.user);

上面的可能有效,问题是我没有信心这实际上是一个好的做法,因为我没有在互联网上找到任何例子关于它。

那么,这是正确的做法吗?有更好/更推荐的方法吗?

最佳答案

这直接取自 redux recipes page :

To pass along the state, we add a tag that will attach preloadedState to window.__PRELOADED_STATE__.

function renderFullPage(html, preloadedState) {
return `
<!doctype html>
<html>
<head>
<title>Redux Universal Example</title>
</head>
<body>
<div id="root">${html}</div>
<script>
// WARNING: See the following for security issues around embedding JSON in HTML:
// http://redux.js.org/docs/recipes/ServerRendering.html#security-considerations
window.__PRELOADED_STATE__ = ${JSON.stringify(preloadedState).replace(/</g, '\\u003c')}
</script>
<script src="/static/bundle.js"></script>
</body>
</html>
`
}

关于javascript - 使用 React/Redux,我如何动态预加载状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43082601/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com