SSR React 与 redux 存储的数据
SSR React with data for redux store
如何在不触发 API (dispatch(action)
) 的情况下用已获取的数据填充存储(在服务器端)?
步骤:
- 客户使用 link
/users
访问网站
- 在服务器上,我将
/users
传递给 StaticRouter
- 在这一步,文档告诉我,我需要递归地调度所有组件(特定于此路由)中的所有操作(又名函数
loadData
),并将获取的数据存储在 redux 存储中。
但是我已经有了所有必要的数据,我不想触发 API。
在此先感谢您的帮助。
您可以使用现有数据手动构建应用程序状态,并从该应用程序状态创建 redux 存储,然后将其传递到全局变量中的客户端。
然后客户端将读取状态并重新水化 redux 存储。以下是未经测试的说明:
服务器端
// ...
// import stuff from places
// ...
// Readily available user data
const users = [{ "_id": 1000, "name": "John Doe" }, { "_id": 2000, "name": "Jane Brown" }];
app.get('/users', (req, res) => {
const context = {};
// Manually construct the redux state
const state = { users: users };
// Create redux store with existing state
const store = createStore(
JSON.stringify(state)
);
const reactDomString = renderToString(
<Provider store={store}>
<StaticRouter context={context} location={req.url}>
<App />
</StaticRouter>
</Provider>
);
res.end(`
<div id="app">${ reactDomString }</div>
<script>
window.REDUX_DATA = ${ JSON.stringify(state) }
</script>
<script src="./app.js"></script>
`);
});
客户端
// ...
// import stuff from places
// ...
// Pick up the data from the SSR template
const store = createStore(window.REDUX_DATA);
const appContainer = document.getElementById("app");
ReactDOM.hydrate(
<ReduxProvider store={store}>
<Router>
<Layout />
</Router>
</ReduxProvider>,
appContainer
);
如何在不触发 API (dispatch(action)
) 的情况下用已获取的数据填充存储(在服务器端)?
步骤:
- 客户使用 link
/users
访问网站
- 在服务器上,我将
/users
传递给StaticRouter
- 在这一步,文档告诉我,我需要递归地调度所有组件(特定于此路由)中的所有操作(又名函数
loadData
),并将获取的数据存储在 redux 存储中。
但是我已经有了所有必要的数据,我不想触发 API。
在此先感谢您的帮助。
您可以使用现有数据手动构建应用程序状态,并从该应用程序状态创建 redux 存储,然后将其传递到全局变量中的客户端。
然后客户端将读取状态并重新水化 redux 存储。以下是未经测试的说明:
服务器端
// ...
// import stuff from places
// ...
// Readily available user data
const users = [{ "_id": 1000, "name": "John Doe" }, { "_id": 2000, "name": "Jane Brown" }];
app.get('/users', (req, res) => {
const context = {};
// Manually construct the redux state
const state = { users: users };
// Create redux store with existing state
const store = createStore(
JSON.stringify(state)
);
const reactDomString = renderToString(
<Provider store={store}>
<StaticRouter context={context} location={req.url}>
<App />
</StaticRouter>
</Provider>
);
res.end(`
<div id="app">${ reactDomString }</div>
<script>
window.REDUX_DATA = ${ JSON.stringify(state) }
</script>
<script src="./app.js"></script>
`);
});
客户端
// ...
// import stuff from places
// ...
// Pick up the data from the SSR template
const store = createStore(window.REDUX_DATA);
const appContainer = document.getElementById("app");
ReactDOM.hydrate(
<ReduxProvider store={store}>
<Router>
<Layout />
</Router>
</ReduxProvider>,
appContainer
);