如何使用redux-saga

时间:2019-09-11 15:46:55

标签: reactjs express webpack redux-saga server-rendering

我是React-Redux应用程序中的新手,并试图在我的应用程序中实现服务器端渲染。我使用redux-saga,webpack和express。

我在浏览器中收到一个错误: TypeError:无法读取未定义的属性“ then”     在评估时(webpack:///./src/serverRenderer.js?:61:25)

运行后

npm run build 
npm run start:dev.

我已经创建了PR https://github.com/milena537blr/epam_react/pull/6

// serverRenderer.js

...
export default function serverRenderer() {
  return (req, res) => {
    const store = configureStore();
     const context = {};

    const renderRoot = () => (
      <Root
        context={context}
        location={req.url}
        Router={StaticRouter}
        store={store}
      />
    );

    store.runSaga().done.then(() => {
      const htmlString = renderToString(renderRoot());

      if (context.url) {
        res.writeHead(302, {
          Location: context.url,
        });
        res.end();
        return;
      }

      const preloadedState = store.getState();

      res.send(renderHTML(htmlString, preloadedState));
    });

    renderToString(renderRoot());
    store.close();
  };
}
...

// server / app.js

...
if (process.env.NODE_ENV === 'development') {
  const webpack = require('webpack');
  const webpackDevMiddleware = require('webpack-dev-middleware');
  const webpackHotMiddleware = require('webpack-hot-middleware');
  const webpackHotServerMiddleware = require('webpack-hot-server-middleware');
  const webpackConfig = require('../webpack');

  const compiler = webpack(webpackConfig);

  app.use(webpackDevMiddleware(compiler));
  app.use(webpackHotMiddleware(compiler.compilers.find(c => c.name === 'client')));
  app.use(webpackHotServerMiddleware(compiler));
} else {
  const serverRenderer = require('../dist/js/serverRenderer').default;

  app.use(express.static('dist'));
  app.use(serverRenderer());
}
...

// package.json

...
"build": "cross-env NODE_ENV=production webpack --config ./webpack",
"start:dev": "cross-env NODE_ENV=development  node ./server",
...

// configureStore.js

...
const sagaMiddleware = createSagaMiddleware();

export default (initialState) => {
  const store = createStore(rootReducer, initialState, applyMiddleware(sagaMiddleware));

  sagaMiddleware.run(rootSaga);
  store.runSaga = () => sagaMiddleware.run(rootSaga);
  store.close = () => store.dispatch(END);

  return store;
};
...

// rootReducer.js

...

function* rootSaga() {
  yield all([
    moviesSaga()
  ]);
}

const rootReducer = combineReducers({
  data,
  filters
});

export { rootReducer, rootSaga };

我希望解决该错误。

0 个答案:

没有答案