首页 文章

Redux getState在服务器上返回initialState

提问于
浏览
0

我正在构建一个同构反应应用程序,并在用户发送请求时执行以下任务:

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 = (
            <StaticRouter location={req.url} context={{}}>
                <Provider store={store}>
                    <App />
                </Provider>
            </StaticRouter>
        )

        const htmlContent = renderToString(content)

        const preloadedState = store.getState() <----- Returns initialState and not the updated state.

        const html = renderToStaticMarkup(<HtmlDocument html={htmlContent} preloadedState={preloadedState} />)

        res.status(200)
        res.send(html)
    })
}
})

aboutPageContainer.jsx

static fetchData = (store) => [store.dispatch(aboutPageContent())]

preloadedState被分配给 window.__data . 并且在client.js上调用 window.__data 以加载客户端存储 .

我做错了吗?这是我的第一个反应 - 同构应用程序 .

1 回答

  • 1

    我认为你需要在这里订阅商店以获得如下更新 . 使用 store.subscribe 将确保您获得更新后的状态 . 希望能帮助到你 . 阅读http://redux.js.org/docs/api/Store.html#subscribelistener

    store.subscribe(() => {
     // When state will be updated(in this case, when items will be fetched), this is how we can get updated state.                    
      let items= store.getState().items;
                  })
    

相关问题