Next-redux-wrapper с next-redux-saga: хранилище создается дважды - PullRequest
0 голосов
/ 28 января 2019

РЕДАКТИРОВАТЬ: Кажется, что-то касается взаимодействия между «next-redux-saga» и новой версией «redux-saga» - я исправил «next-redux-saga» локально, чтобы он работалс '1.0.0', но при возврате и возвращении к 'redux-saga' 0.16.0 проблема ниже исчезла.Я буду исследовать дальше

Я подключаю Next.js к редуксу к своему приложению реакции, используя next-redux-wrapper и next-redux-saga.Это работает противоречиво.Я провел некоторую отладку и обнаружил, что моя пользовательская функция createStore вызывается дважды: один раз при первой загрузке приложения, непосредственно перед getInitialProps в _app.js, а затем снова сразу после того, как pageProps = await Component.getInitialProps({ctx}); вернется в _app.js.

Я использовал пример кода redux-saga с сайта Next.js - Помимо того, что в приложении проекта происходит много других вещей, которых нет в примере приложения Next.js,самое большое отличие состоит в том, что поставщик магазина окружает компонент Layout в _app.js, и он, в свою очередь, содержит три компонента, один для верхнего колонтитула, один для нижнего колонтитула и один для основного содержимого - каждый из них связан с хранилищем.

Вот след того, что происходит - это как мои console.logs, так и операторы отладки next-redux-wrapper.Когда данные или реквизиты получены правильно, я указываю это, хотя я не печатаю все данные ниже (они появляются в журнале).В конце журнала вы увидите, что данные не получены правильно.

Спасибо за помощь!

   creating store::::
1. WrappedApp.getInitialProps wrapper got the store with state { home: {} }
_app.js getInitialProps
calling Component.getInitialProps
index.js, getInitialProps isServer =  true
index.js, dispatching saga loadData inside index.js getInitialProps, isServer =  true
fetching data in saga from route home:  http://something.else.com/api/es/
returning Component.getInitialProps
storing data in store { name: 'Home',
  published: true,
  draft: false,
  layout_id: 1,}
3. WrappedApp.getInitialProps has store state { home:
   { data:... } // data received correctly
4. WrappedApp.render created new store with initialState { home:
     { data:... } // data received correctly
creating store::::
rendering _app.js, main render, props =  { Component:
   { [Function: Connect]
     WrappedComponent: { [Function: Index] propTypes: [Object] },
     displayName: 'Connect(Index)' },
  router:
   Router {
     onPopState: [Function],
     route: '/index',
     components: { '/_app': [Object] },
     events: EventEmitter { listeners: {} },
     pageLoader: undefined,
     prefetchQueue:
      PQueue {
        queue: [Queue],
        _pendingCount: 0,
        _concurrency: 2,
        _resolveEmpty: [Function] },
     ErrorComponent: undefined,
     pathname: '/index',
     query: {},
     asPath: '/',
     subscriptions: Set { _c: Set {} },
     componentLoadCancel: null,
     _beforePopState: [Function] },
  isServer: true,
  store:
   { dispatch: [Function],
     subscribe: [Function: subscribe],
     getState: [Function: getState],
     replaceReducer: [Function: replaceReducer],
     runSagaTask: [Function],
     sagaTask:
      { '@@redux-saga/TASK': true,
        id: 10,
        meta: [Object],
        isRoot: true,
        context: {},
        joiners: null,
        queue: [Object],
        cancel: [Function: cancel],
        cont: [Function],
        end: [Function: end],
        setContext: [Function: setContext],
        toPromise: [Function: toPromise],
        isRunning: [Function: isRunning],
        isCancelled: [Function: isCancelled],
        isAborted: [Function: isAborted],
        result: [Function: result],
        error: [Function: error] },
     [Symbol(observable)]: [Function: observable] } }
in header.js selector, state =  { home:
     { data:... } // data received correctly
rendering Header.js, props =  { headerData:...} // props received correctly
rendering index.js, props =  {...,} // props received correctly
rendering Footer.js, props =  {...,} // props received correctly
creating store::::
1. WrappedApp.getInitialProps wrapper got the store with state { home: {} }
_app.js getInitialProps
calling Component.getInitialProps
index.js, getInitialProps isServer =  true data =  undefined
index.js, dispatching loadData inside index.js getInitialProps, isServer =  true
returning Component.getInitialProps
3. WrappedApp.getInitialProps has store state { home: {} }
4. WrappedApp.render created new store with initialState { home: {} } // store is EMPTY
creating store::::
rendering _app.js, // props are NOT received correctly
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...