我正在关注Nextjs + mobx example,但是我无法通过api调用来填充商店。
在我看来,HOC的以下部分实际上并没有等待页面的getInitialProps解析,而是继续执行:
if (typeof App.getInitialProps === "function") {
appProps = await App.getInitialProps.call(App, appContext)
}
更具体地说,尽管有await
状态执行仍继续执行,并且不进行任何初始化存储,而不是等待api数据继续执行。
由于各种console.log
语句会产生以下输出,因此我也可以这样说-我可以看到在页面的getInitialProps中完成api请求之前,HOC(以及商店)的初始化完成了。 / p>
HOC initial props
Page initial props started
HOC initial props complete
HOC constructor
Page initial props complete
关于我在这里做错的任何想法吗?
getInitialProps和索引页的导出:
Index.getInitialProps = async function(ctx) {
console.log("Page initial props started")
const r = await ctx.store.postStore.getQuestions()
console.log("Page initial props complete")
return r
}
export default WithAuth(withLayout(withStyles(styles)(Index)))
调用api并填充商店的商店方法:
getQuestions() {
return apiGetQuestions().then(res => {
// console.log("received data")
return (
res.data.questions.length > 0 &&
(this.posts = res.data.questions.map(
json => new Question(json)
))
)
})
API调用功能:
export const apiGetQuestions = () => {
return fetch(`${url}/api/questions`, {
headers: {
"Content-Type": "application/json",
mode: "cors",
"Access-Control-Allow-Origin": "http://localhost:3000/"
},
method: "GET"
})
.then(response => response.json())
.catch(e => {
throw "Unable to save record"
})
}
HOC的getInitialProps:
static async getInitialProps(appContext) {
console.log("HOC initial props")
const store = getOrCreateStore()
appContext.ctx.store = store
let appProps = {}
if (typeof App.getInitialProps === "function") {
appProps = await App.getInitialProps.call(App, appContext)
}
console.log("HOC initial props complete")
return {
...appProps,
initialMobxState: store
}
}