我正在使用 React、redux、react-router、react-router-redux 编写同构应用程序。
我在 client.js 上调用 syncHistoryWithStore
。但在初始加载时,router.locationBeforeTransitions
始终为 null。不过,一旦我导航,它就会被填充。
const history = syncHistoryWithStore(browserHistory, store);
...
<Router routes={routes} history={history} />
以上代码来自client.js
我是否应该在服务器端手动触发 LOCATION_CHANGE
操作以填充 react-router-redux 的初始状态?
最佳答案
您将在客户端创建一个新商店,因此在服务器上创建的商店的状态将丢失。我们需要将初始状态从服务器传递到客户端,以便它可以填充其存储。
在服务器上:
const initialState = store.getState();
现在将其添加到从服务器呈现的 HTML 模板中:
<script type="application/javascript">
window.__INITIAL_STATE__ = ${JSON.stringify(initialState)};
</script>
在客户端:
let initialState = window.__INITIAL_STATE__;
当你 createStore
时使用 initialState
在客户端上。
关于javascript - 在同构应用程序上 react 路由器 redux 初始状态设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40711199/