【发布时间】:2018-06-04 02:45:37
【问题描述】:
我正在努力让服务器端渲染 (SSR) 与 redux-api 一起使用。该应用仅适用于客户端渲染 (CSR)。
为了让 SSR 工作,我需要在 Next.js 的 getInitialProps 函数中提供数据。我正在尝试使用next-redux-wrapper 将其绑定在一起。
当前状态:
class ShowLessonPage extends React.Component {
static async getInitialProps ({store, isServer, pathname, query}) {
console.log(`getInitialProps`, {store, isServer, pathname, query});
const { dispatch } = store;
const lessonSlug = query.lessonSlug;
// Get one Lesson
dispatch(reduxApi.actions.oneLesson({ id: `slug=${lessonSlug}` }));
}
render() {
console.log('render', this.props.oneLesson);
const lesson = this.props.oneLesson.data;
//...
}
//.....
}
const createStoreWithThunkMiddleware = applyMiddleware(thunk)(createStore);
const reducer = combineReducers(myReduxApi.reducers); // redux-api
const makeStore = function (state, enhancer) {
return createStoreWithThunkMiddleware(reducer, state);
}
const mapStateToProps = function (state) {
return { oneLesson: state.oneLesson };
};
// withRedux = next-redux-wrapper
const ShowLessonPageConnected = withRedux({ createStore: makeStore, mapStateToProps: mapStateToProps })(ShowLessonPage)
export default ShowLessonPageConnected;
我现在至少将store 加入getInitialProps,但我收到了一条奇怪的Error: only absolute urls are supported 消息,我的CSR(withRedux 之前)版本的应用程序中没有。而this.props.oneLesson.data 当然是空的。
makeStore 在服务器生成的调用上得到一个state=undefined,也许这是一个线索。
我也愿意用其他类似的东西替换 redux-api。
更新 1: 通过将所有 URL 填满,Redux 现在正在访问我的 API 端点。但是,对于 1 页重新加载,它调用 makeStore 不少于 3 次,并且只有第一个调用包含正确的 slug,请参阅控制台输出:
makeStore { state: undefined, reqParams: { lessonSlug: 'tyrannosaurus-rex' } }
getInitialProps { query: { lessonSlug: 'tyrannosaurus-rex' } }
API: GET request: { _id: 'slug=tyrannosaurus-rex' }
makeStore { state: undefined, reqParams: { lessonSlug: 'undefined' } }
getInitialProps { query: { lessonSlug: 'undefined' } }
API: GET request: { _id: 'slug=undefined' }
makeStore { state: undefined, reqParams: { lessonSlug: 'undefined' } }
getInitialProps { query: { lessonSlug: 'undefined' } }
API: GET request: { _id: 'slug=undefined' }
更新 2: 突破:从getInitialProps 返回一个承诺使 SSR 工作。现在客户端渲染开始起作用了,很有趣。
static async getInitialProps ({store, isServer, pathname, query}) {
const { dispatch } = store;
const lessonSlug = query.lessonSlug;
const resultPromise = await dispatch(reduxApi.actions.oneLesson({ id: `slug=${lessonSlug}` }));
return resultPromise;
}
【问题讨论】:
标签: javascript redux next.js nextjs redux-api-middleware