【发布时间】:2015-06-21 08:34:55
【问题描述】:
我有一个带有多个视图的反应应用程序(例如Profile、Followers)。这些视图中的每一个当前都作为它自己的 React 组件存在,该组件在服务器端和客户端执行。我开始难以理解构建代码的正确方法。
例如,假设 Profile 已加载并且用户点击“查看关注者”。此时,调度员会收到一条消息,上面写着gotoFollowers。在顶层,我们渲染一个全新的 React 组件(即Followers 组件)。不幸的是,Follower 和 Profile 组件都需要类似的数据(例如会话数据、用户照片、用户名,甚至关注者,因为我们在 Profile 上显示了关注者的 sn-p)。因此,每次用户更改页面时都必须在顶层重新渲染(包括进行 ajax 调用)感觉非常浪费。
我认为我没有正确执行此操作。我应该使用单个父 React 组件吗? (我也看到了问题)我应该如何构建具有许多视图的大型 React 应用程序?
window.render = function (page, id, pushState) {
var stateURL = '';
switch (page) {
case 'Profile':
stateURL = '/' + id;
async.parallel({
profileData: function (callback) { MemberLoader.load(id, callback); },
followerData: function (callback) { FollowerLoader.load(id, callback); },
},
sessionData: function (callback) { Session.get(callback); },
}, function (err, results) {
var component = React.createFactory(Profile);
React.render(component({ member: results.profileData, followers: results.followerData, session: results.sessionData }), mountNode);
});
break;
case 'Followers':
stateURL = '/' + id + '/followers';
async.parallel({
profileData: function (callback) { MemberLoader.load(id, callback); },
sessionData: function (callback) { Session.get(callback); },
followerData: function (callback) { FollowerLoader.load(id, callback); },
}, function (err, results) {
var component = React.createFactory(Followers);
React.render(component({ member: results.profileData, followers: results.followerData, session: results.sessionData }), mountNode);
});
break;
};
if (pushState) {
window.history.pushState({ page: page, id: id }, null, stateURL);
} else {
window.history.replaceState({ page: page, id: id }, null, stateURL);
}
};
Dispatcher.register(function(event) {
if (event.action === 'gotoProfile') {
window.render('Profile', event.username, true);
}
else if (event.action === 'gotoFollowers') {
window.render('Followers', event.username, false);
}
});
注意:我们的应用程序在服务器端和客户端都呈现。
【问题讨论】:
标签: javascript reactjs reactjs-flux