我正在构建一个同构反应应用程序,并在用户发送请求时执行以下任务:
1)假设用户命中 /about-us ,react-routers matchPath 找到适当的组件并返回它 .
2)调用名为fetchData的静态函数,该函数调度动作 aboutPageContent() . 3)一旦在服务器上解析了promise,就会调用getState以获得更新状态 but it returns the initialState of aboutPage and not the newly updated state .
Reducer获得响应但不返回新状态 . (只有在服务器调度操作时才会发生这种情况) .
服务器上的getState返回:
{
aboutUs:{
founders:[{}]
story: ""
}
}
但它应该返回:
{
aboutUs:{
founders:[{name: 'abc'}]
story: "some random story"
}
}
server.js
app.get("*", (req, res) => {
const memoryHistory = createMemoryHistory(req.url)
const currentRoute = routes.find(r => matchPath(req.url, r))
const store = configureStore({}, memoryHistory)
if (currentRoute && currentRoute.component.fetchData) {
Promise.all(currentRoute.component.fetchData(store, req.url)).then(() => {
const content = (
)
const htmlContent = renderToString(content)
const preloadedState = store.getState()
const html = renderToStaticMarkup()
res.status(200)
res.send(html)
})
}
})
aboutPageContainer.jsx
static fetchData = (store) => [store.dispatch(aboutPageContent())]
preloadedState被分配给 window.__data . 并且在client.js上调用 window.__data 以加载客户端存储 .
我做错了吗?这是我的第一个反应 - 同构应用程序 .