Dav*_*lva 6 reactjs redux server-side-rendering redux-saga next.js
我完成了使用 create-react-app (CSR) 创建的 React 应用程序的编码,但现在我正在使用 Next.js 框架重写整个应用程序,以获得更好的 SEO 性能。
在重写它时,我很难弄清楚如何正确处理 redux 和 redux-saga 来执行获取和存储数据过程。在这个项目中使用 Next.js 的主要原因是利用 getInitialProps 方法,在第一个页面加载发生之前获取服务器端的数据。但由于某种原因,我无法“等待”Redux 调度完成并按时获取获取的数据。
所以最终发生的情况是,我调度了获取数据的操作,但在初始服务器端页面加载期间它没有按时存储在 redux 存储中。但是,当我使用 next/link 更改路由时,数据会进入,但仅在客户端渲染发生后。
所以它有点违背了使用 Next.js 的目的。
这个新代码与 create-react-app 项目非常相似,只是进行了一些细微的更改以适应 Next.js 项目的要求。
这是我的代码。
./pages/_app.js
import App from 'next/app';
import { Provider } from 'react-redux';
import withRedux from 'next-redux-wrapper';
import withReduxSaga from 'next-redux-saga';
import makeStore from '../store/index';
class MyApp extends App {
static async getInitialProps({ Component, ctx }) {
const pageProps = Component.getInitialProps
? await Component.getInitialProps(ctx)
: {};
return { pageProps };
}
render() {
const { Component, pageProps, store } = this.props;
return (
<Provider store={store}>
<Component {...pageProps} />
</Provider>
);
}
}
export default withRedux(makeStore)(MyApp);
Run Code Online (Sandbox Code Playgroud)
./pages/index.jsx:
import App from 'next/app';
import { Provider } from 'react-redux';
import withRedux from 'next-redux-wrapper';
import withReduxSaga from 'next-redux-saga';
import makeStore from '../store/index';
class MyApp extends App {
static async getInitialProps({ Component, ctx }) {
const pageProps = Component.getInitialProps
? await Component.getInitialProps(ctx)
: {};
return { pageProps };
}
render() {
const { Component, pageProps, store } = this.props;
return (
<Provider store={store}>
<Component {...pageProps} />
</Provider>
);
}
}
export default withRedux(makeStore)(MyApp);
Run Code Online (Sandbox Code Playgroud)
./store/index.js
import {
createStore,
applyMiddleware,
compose,
} from 'redux';
import createSagaMiddleware, { END } from 'redux-saga';
import rootReducer from './reducers';
import rootSaga from './sagas';
const sagaMiddleware = createSagaMiddleware();
const makeStore = (initialState) => {
const composeEnhancers = (typeof window !== 'undefined' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__) || compose;
const store = createStore(
rootReducer,
initialState,
compose(
composeEnhancers(applyMiddleware(sagaMiddleware)),
),
);
store.runSaga = () => {
if (store.saga) {
return;
}
store.sagaTask = sagaMiddleware.run(rootSaga);
};
store.stopSaga = async () => {
if (!store.saga) {
return;
}
store.dispatch(END);
await store.saga.done;
store.saga = null;
};
store.execSagaTasks = async (isServer, tasks) => {
store.runSaga();
tasks(store.dispatch);
await store.stopSaga();
if (!isServer) {
store.runSaga();
}
};
store.runSaga();
return store;
};
export default makeStore;
Run Code Online (Sandbox Code Playgroud)
./store/actions/blog/blog.js
export function getRecentCategories(number) {
return {
type: 'REQUEST_RECENT_CATEGORIES',
payload: {
number,
},
};
}
Run Code Online (Sandbox Code Playgroud)
./store/reducers/blog/blog.js
import update from 'immutability-helper';
const initialState = {
blogCategories: {
data: [],
loading: false,
fetched: false,
error: false,
},
};
export default function blog(state = initialState, action) {
switch (action.type) {
case 'REQUEST_RECENT_CATEGORIES':
return update(state, {
blogCategories: {
loading: { $set: true },
},
});
case 'SUCCESS_RECENT_CATEGORIES':
console.log('actions:', action.payload.data);
//output: actions: blogCategories [ 'test1', 'category', 'crypto', 'test4', 'Day trade' ]
return update(state, {
blogCategories: {
data: { $set: action.payload.data },
loading: { $set: false },
fetched: { $set: true },
error: { $set: false },
},
});
case 'FAILURE_RECENT_CATEGORIES':
return update(state, {
blogCategories: {
fetched: { $set: true },
error: { $set: true },
},
});
default:
return state;
}
}
Run Code Online (Sandbox Code Playgroud)
./store/sagas/blog/getRecentCategories.js
import {
put,
call,
} from 'redux-saga/effects';
import 'isomorphic-fetch';
async function getRecentCategoriesApi(number) {
const res = await fetch(`http://localhost:5000/blog/get/categories/newest/${number}`, {
method: 'GET',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
},
});
const data = await res.json();
return data;
}
export default function* asyncGetRecentCategoriesApi(action) {
try {
const response = yield call(getRecentCategoriesApi, action.payload.number);
yield put({ type: 'SUCCESS_RECENT_CATEGORIES', payload: { data: response } });
} catch (err) {
yield put({ type: 'FAILURE_RECENT_CATEGORIES' });
}
}
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,这个应用程序是一个非常普通的 React redux-saga 应用程序。除了使用 redux-saga 从后端获取数据之外,其他一切都正常工作。
有什么方法可以使 getInitialProps 方法按预期与 redux 和 redux-saga 一起使用吗?
查看官方 Next.js 示例和 redux-saga 示例。
https://github.com/zeit/next.js/tree/canary/examples/with-redux-saga
| 归档时间: |
|
| 查看次数: |
6745 次 |
| 最近记录: |