我正在尝试使用Redux和Redux-saga进行React SSR。
我能够使客户端呈现正常工作,但是服务器存储似乎从未获得数据/在呈现HTML之前等待数据。
import {createStore, applyMiddleware} from "redux";
import createSagaMiddleware from "redux-saga";
import rootSaga from "../client/saga";
import reducers from '../client/reducers';
export default () => {
const sagaMiddleware = createSagaMiddleware();
const store = createStore(
reducers,
{},
applyMiddleware(sagaMiddleware));
store.runSaga = sagaMiddleware.run; // added after research to
store.close = () => store.dispatch(END); // added after research no effect
return store;
}
server.js
import express from 'express';
import renderer from "./helpers/renderer";
import createStore from "./helpers/createStore";
import {matchRoutes} from 'react-router-config';
import Routes from "./client/Routes";
import rootSaga from "./client/saga";
const app = express();
app.use(express.static('public'));
app.get('*', (req, res) => {
const store = createStore();
const branch = matchRoutes(Routes, req.path);
const promises = branch.map(({ route }) => {
return route.loadData ? route.loadData(store) : Promise.resolve(null);
});
store.runSaga(rootSaga).done.then(() => {
res.send(renderer(req, store)) // helper method to load static router and provider
})
});
app.listen(3000, () => {
console.log('Listening on Port 3000');
})
小传奇
import { put, takeEvery, all, call } from 'redux-saga/effects'
import {FETCH_USERS, SAVE_USERS} from "../actions";
import axios from 'axios';
export function* fetchUsers() {
const res = yield call(getUsers);
yield put({ type: SAVE_USERS, payload: res.data});
}
const getUsers = async () => {
const response = await axios.get('http://react-ssr-api.herokuapp.com/users');
return response;
}
export function* actionWatcher() {
yield takeEvery(FETCH_USERS, fetchUsers)
}
export default function* rootSaga() {
yield all([
actionWatcher()
])
}
错误
TypeError:无法读取未定义的属性'then'在/Users/rahsinwb/Documents/Mine/code/SSR/build/bundle.js:309:39
我在这里想念的是什么?还是有任何经过验证的方式可以侦听传奇故事的结束,我当时在想我组件中带有store.dispatch
的loadData辅助函数用于初始操作调用将返回promise,但它永远不会起作用。
LoadData
const loadData = (store) => {
store.dispatch({type: FETCH_USERS});
}
我相信.done
已已弃用。您应该改用.toPromise
。
store.runSaga(rootSaga).toPromise().then(() => {
Edit:call
效果需要一个返回Promise的函数。您的函数返回一个对象。
修改您的getUsers
功能:
const getUsers = () => {
return axios.get('http://react-ssr-api.herokuapp.com/users');
}