javascript - Redux getState 返回服务器上的初始状态

标签 javascript reactjs redux isomorphic-javascript

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

1) 假设用户点击 /about-us,react-routers matchPath 找到合适的组件并返回它。
2) 调用名为 fetchData 的静态函数,该函数分派(dispatch)操作 aboutPageContent()。 3) 一旦在服务器上解决了 Promise,就会调用 getState 来获取更新的状态,但它返回 aboutPage 的初始状态,而不是新更新的状态

Reducer gets a response but does not return a new state. (this happens only when action is dispatched by server).

服务器上的 getState 返回:

{
   aboutUs:{
      founders:[{}]
      story: ""
   }
}

但它应该返回:

{
  aboutUs:{
    founders:[{name: 'abc'}]
    story: "some random story"
  }
}

服务器.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 以加载客户端存储。

我做错了什么吗?这是我的第一个 react 同构应用程序。

最佳答案

我认为您需要订阅此处的商店才能获取如下更新。 使用 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;
              })

关于javascript - Redux getState 返回服务器上的初始状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46261148/

相关文章:

javascript - Bootstrap 导航 - 手机

javascript - 如何在 react 中的不同组件库之间共享上下文?

javascript - react redux normalizr : how to deal with nested entities?

javascript - 如何使用 Firebase 函数从 Firestore 获取值(value)?

javascript - 为什么 JSON.stringify 添加额外的 ""

reactjs - Jest 测试在 react 加载中失败

javascript - ES6 '...' 符号在 jslint 中给出错误?

Redux 操作没有被触发

javascript - Redux:Reducer 需要其他 Reducer 的状态?

javascript - 为什么 Array.prototype.includes.bind 行为异常?