[英]React/Redux preloading content from API response before page renders
我目前正在構建一個包含菜單的Web應用程序。 菜單可能會根據幾個變量而變化,因此我調用了api,以請求應顯示的正確菜單項。
server.get('/api/getMenu', (req, res) => {
getMenu((err, content) => {
if(!err) {
res.send(content);
} else {
res.status(500).send();
}
})
});
此請求工作正常,然后我調度一個將在componentWillMount上調用此API的操作
export function fetchMenuItems() {
return (dispatch) => {
fetch('/api/getMenu')
.then((response) => {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
})
.then((response) => response.json())
.then((results) => dispatch(fetchSuccess(results)))
}
}
export function fetchSuccess(results) {
return {
type: 'FETCH_SUCCESS',
menuItems: results
};
}
這再次可以正常工作並加載菜單項,但是看起來很奇怪,因為菜單項似乎在頁面其余部分已經加載之后呈現在頁面上(我假設是由於請求花費了多長時間)。
有沒有辦法在整個頁面實際呈現之前預加載菜單項? 我聽說過諾言,但是對諾言的了解甚少,這可能是一個解決方案嗎?
我假設您正在尋找componentWillMount反應生命周期方法。
僅在第一次渲染組件之前, componentWillMount
將僅被調用一次。 這是放置任何預加載數據邏輯的理想場所。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.