我们有一个React App,现在我们想使其成为同构(SSR)。 我们深深地使用Redux。所有的xhr请求都通过Redux动作并保存在reducer上。
我对react ssr有疑问。
1。我应该对此流程使用同构提取吗?或者我可以改用axios?
2。在执行动作分派和接收到数据时,server.js中的存储没有更新。我该怎么办?
我们有一些页面希望urlParams调度操作。
这是我们的Express服务器文件:
import cStore from './store'
app.use(express.static(path.resolve(__dirname, "../dist")));
app.use('/public', express.static(path.resolve(__dirname, "../public")));
app.use(cors())
app.get("*", (req, res, next) => {
const store = cStore();
const context = {};
const dataRequirements =
routes
.filter(route => matchPath(req.url, route)) // filter matching paths
.map(route => route.component) // map to components
.filter(comp => comp.fetchMe) // check if components have data requirement
.map(comp => {
comp.fetchMe(store, req.params[0])
}); // dispatch data requirement
如您在上面的片段中看到的,我在每条路由上调度fetchMe操作,并将存储和url发送到映射的组件,并将store.getState()保存在window.REDUX_DATA
这是我的组件fetchMe操作之一:
Tour.fetchMe = (store, obj) => {
let tourId = obj.split("/").pop() //split last part of url that show me tourId
store.dispatch(fetchTourData(tourId))
}
这是我的store.js文件,我从那里分发操作,结合了reducer和创建redux存储的cStore函数位于此处:
import { createStore, combineReducers, applyMiddleware } from "redux";
import thunkMiddleware from "redux-thunk";
import { fetchToursIso } from "./store/isomorphic/api";
const storeTourData = (res) => ({
type: "FETCH_TOUR_FULFILLED",
payload: res,
});
const tourReducer = (state = [], action) => {
switch (action.type) {
case "FETCH_TOUR_FULFILLED":
return action.data;
default: return state;
}
};
export const fetchTourData = (tourId) => (dispatch) => {
fetchToursIso(tourId).then(res => {
dispatch(storeTourData(res))
})
};
const reducer = combineReducers({
tour: tourReducer,
});
export default (initialState) =>
createStore(reducer, initialState, applyMiddleware(thunkMiddleware));
此流程正确吗?或者我必须使用另一种方法。
谢谢。