我目前正在构建一个包含菜单的网络应用。菜单可以根据几个变量而改变,所以我打电话给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
};
}
这再次正常工作并加载菜单项,但它看起来很奇怪,因为菜单项似乎在页面的其余部分已经加载后在页面上呈现(我假设由于请求有多长需要)。
有没有办法在整个页面实际呈现之前预加载菜单项?我已经听说过承诺,但对它们知之甚少,这可能是一个解决方案吗?
答案 0 :(得分:0)
我假设您正在寻找componentWillMount反应生命周期方法。
componentWillMount
只会在第一次呈现组件之前调用一次。这是放置任何预装数据逻辑的理想场所。
希望这有帮助。