在getInitialProps内部调度动作

时间:2019-12-14 20:35:12

标签: express authentication redux next.js

我正在使用外部Express服务器和下一个js编写简单的用户身份验证。 我已经通过next-redux-wrapper

redux用作全局状态管理器

_app.js


const MyApp = ({ Component, pageProps, store }) => {
  return (
    <Provider store={store}>
      <Page>
        <Component {...pageProps} />
      </Page>
    </Provider>
  )
}

MyApp.getInitialProps = async ({ Component, ctx }) => {
  checkServerSideCookie(ctx)
  const pageProps = Component.getInitialProps
    ? await Component.getInitialProps(ctx)
    : {}

  return { pageProps }
}
export default withRedux(makeStore)(MyApp)

当我在下一个应用程序的客户端时,身份验证非常有用。登录后,令牌将与cookie一起接收,而用户数据将与响应一起。

问题是当我刷新页面时,用户信息丢失。为了取回数据并保存到还原状态,我在checkServerSideCookie(ctx)内部使用了_app.js操作来验证服务器端的用户。

export const checkServerSideCookie = ctx => {
  if (ctx.req) {
    const cookies = nookies.get(ctx)
    const user = getUser(cookies).then(user => {
      ctx.store.dispatch({ type: AUTHENTICATE, payload: user })
    })
  } else {
    console.log("on browser")
  }
}

getUser()是一个API调用,用于从Express服务器获取数据。 很好地获取了用户,但是调度无法实现,因为它位于promise的解决方案之内。你能帮我吗?

0 个答案:

没有答案