简体   繁体   English

使用redux-saga反应服务器端渲染

[英]React server side rendering with redux-saga

I have saga implemented as 我的传奇实现为

import { put, takeLatest } from 'redux-saga/effects';
import axios from 'axios';

import { FETCH_CARD_LIST_DATA_FROM_API, SET_CARD_LIST  } from 
'./CardList.actions';
import constants from '../../../../constants';

export default function * fetchCardListSaga(){
 yield takeLatest(FETCH_CARD_LIST_DATA_FROM_API, fetchDataFromAPI)
}



function * fetchDataFromAPI(action){
const { payload } = action;
const response = yield 
axios.get(`${constants.API_URL}/hotels/${payload[0]}/${payload[1]}`);
  console.log('data recieved from api server', response.data.length);
if(response.status === 200){
  yield put({
    type: SET_CARD_LIST,
    payload: response.data
  });
 }
}

At server.js 在server.js

const sagaMiddleWare = createSagaMiddleware();
const store =  createStore(rootReducer, initialState, 
applyMiddleware(sagaMiddleWare));
sagaMiddleWare.run(fetchCardListSaga);

Now how do i dispatch action so that the data is fetched from API server and then i call res.send on server. 现在我该如何调度操作,以便从API服务器获取数据,然后在服务器上调用res.send。

I know how to make it work at client side using react-redux. 我知道如何使用react-redux在客户端运行它。 The problem on server side is how to dispatch action and how to wait before sending response from server till store is updated. 服务器端的问题是如何调度动作以及如何等待从服务器发送响应直到存储更新。

Tricky. 棘手。

You can dispatch actions by getting your store reference and calling store.dispatch , but you can't wait on the saga. 您可以通过获取store引用并调用store.dispatch来调度操作,但是您不能等待这个传奇。 And you can't call the saga manually and yield on it, as it depends on the saga middleware. 而且您不能手动调用saga并使其yield ,因为它取决于saga中间件。

I would put the request in a helper function and do that data fetching on the server without the saga and dispatch this way the response. 我会将请求放入一个辅助函数中,并在不加传奇的情况下在服务器上进行数据获取,并以此方式分配响应。 And use the same helper function in the saga. 并在传奇中使用相同的辅助函数。

Honestly, I wouldn't use middlewares for SSE. 老实说,我不会在SSE中使用中间件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM