(注意:我使用了JSX Harmony选项的ES6语法。)
作为练习,我编写了一个示例Flux应用程序,允许浏览Github用户和repos。
它基于fisherwebdev的答案,但也反映了我在规范化API响应方面使用的方法。
我做这件事是为了记录我在学习Flux时尝试过的一些方法。
我试图保持接近现实世界的情况(分页,没有虚假的localStorage API)。
这里有一些我特别感兴趣的东西:
我如何分类Store
我尝试避免在其他Flux示例中看到的一些重复,特别是在Stores中。
我发现将Stores在逻辑上分成三类非常有用:
内容Stores保存所有应用程序实体。具有ID的所有内容都需要自己的Content Store。呈现单个项目的组件从Content Stores请求最新数据。
Content Stores从所有服务器操作中收集它们的对象。例如,UserStore
查看action.response.entities.users
是否存在,无论哪个动作启动,都可以使用这些对象。没有必要使用switch。Normalizr使任何API响应易于转换成此格式。
// Content Stores keep their data like this
{
7: {
id: 7,
name: 'Dan'
},
...
}
列表存储跟踪在某个全局列表(例如“动态”,“你的通知”)中出现的实体的ID。在这个项目中,我没有这样的存储,但我还是想提一下它们。它们处理分页。
它们通常只响应几个操作(例如
REQUEST_FEED
,
REQUEST_FEED_SUCCESS
,
REQUEST_FEED_ERROR
)。
// Paginated Stores keep their data like this
[7, 10, 5, ...]
索引列表存储(Indexed List Stores)类似于列表存储(List Stores),但它们定义了一对多的关系。例如,“用户的订阅者”、“仓库的点赞者”、“用户的软件库”。它们还处理分页。
通常也会响应少数几个操作(例如:REQUEST_USER_REPOS
、REQUEST_USER_REPOS_SUCCESS
、REQUEST_USER_REPOS_ERROR
)。
在大多数社交应用中,您将拥有大量这些内容,并且希望能够快速创建更多这样的内容。
{
2: [7, 10, 5, ...],
6: [7, 1, 2, ...],
...
}
注意:这些不是真正的类或者什么东西;这只是我对Stores的一种思考方式。但我创建了几个辅助工具。
createStore
这个方法提供给你最基本的Store:
createStore(spec) {
var store = merge(EventEmitter.prototype, merge(spec, {
emitChange() {
this.emit(CHANGE_EVENT);
},
addChangeListener(callback) {
this.on(CHANGE_EVENT, callback);
},
removeChangeListener(callback) {
this.removeListener(CHANGE_EVENT, callback);
}
}));
_.each(store, function (val, key) {
if (_.isFunction(val)) {
store[key] = store[key].bind(store);
}
});
store.setMaxListeners(0);
return store;
}
我用它来创建所有的商店。
isInBag
, mergeIntoBag
这些小助手对内容存储非常有用。
isInBag(bag, id, fields) {
var item = bag[id];
if (!bag[id]) {
return false;
}
if (fields) {
return fields.every(field => item.hasOwnProperty(field));
} else {
return true;
}
},
mergeIntoBag(bag, entities, transform) {
if (!transform) {
transform = (x) => x;
}
for (var key in entities) {
if (!entities.hasOwnProperty(key)) {
continue;
}
if (!bag.hasOwnProperty(key)) {
bag[key] = transform(entities[key]);
} else if (!shallowEqual(bag[key], entities[key])) {
bag[key] = transform(merge(bag[key], entities[key]));
}
}
}
用于存储分页状态并执行某些断言(例如,在获取数据时不能获取页面等)。
class PaginatedList {
constructor(ids) {
this._ids = ids || [];
this._pageCount = 0;
this._nextPageUrl = null;
this._isExpectingPage = false;
}
getIds() {
return this._ids;
}
getPageCount() {
return this._pageCount;
}
isExpectingPage() {
return this._isExpectingPage;
}
getNextPageUrl() {
return this._nextPageUrl;
}
isLastPage() {
return this.getNextPageUrl() === null && this.getPageCount() > 0;
}
prepend(id) {
this._ids = _.union([id], this._ids);
}
remove(id) {
this._ids = _.without(this._ids, id);
}
expectPage() {
invariant(!this._isExpectingPage, 'Cannot call expectPage twice without prior cancelPage or receivePage call.');
this._isExpectingPage = true;
}
cancelPage() {
invariant(this._isExpectingPage, 'Cannot call cancelPage without prior expectPage call.');
this._isExpectingPage = false;
}
receivePage(newIds, nextPageUrl) {
invariant(this._isExpectingPage, 'Cannot call receivePage without prior expectPage call.');
if (newIds.length) {
this._ids = _.union(this._ids, newIds);
}
this._isExpectingPage = false;
this._nextPageUrl = nextPageUrl || null;
this._pageCount++;
}
}
createListStore
, createIndexedListStore
, createListActionHandler
提供模板方法和操作处理,使得创建索引列表存储尽可能简单。
var PROXIED_PAGINATED_LIST_METHODS = [
'getIds', 'getPageCount', 'getNextPageUrl',
'isExpectingPage', 'isLastPage'
];
function createListStoreSpec({ getList, callListMethod }) {
var spec = {
getList: getList
};
PROXIED_PAGINATED_LIST_METHODS.forEach(method => {
spec[method] = function (...args) {
return callListMethod(method, args);
};
});
return spec;
}
function createListStore(spec) {
var list = new PaginatedList();
function getList() {
return list;
}
function callListMethod(method, args) {
return list[method].call(list, args);
}
return createStore(
merge(spec, createListStoreSpec({
getList: getList,
callListMethod: callListMethod
}))
);
}
function createIndexedListStore(spec) {
var lists = {};
function getList(id) {
if (!lists[id]) {
lists[id] = new PaginatedList();
}
return lists[id];
}
function callListMethod(method, args) {
var id = args.shift();
if (typeof id === 'undefined') {
throw new Error('Indexed pagination store methods expect ID as first parameter.');
}
var list = getList(id);
return list[method].call(list, args);
}
return createStore(
merge(spec, createListStoreSpec({
getList: getList,
callListMethod: callListMethod
}))
);
}
function createListActionHandler(actions) {
var {
request: requestAction,
error: errorAction,
success: successAction,
preload: preloadAction
} = actions;
invariant(requestAction, 'Pass a valid request action.');
invariant(errorAction, 'Pass a valid error action.');
invariant(successAction, 'Pass a valid success action.');
return function (action, list, emitChange) {
switch (action.type) {
case requestAction:
list.expectPage();
emitChange();
break;
case errorAction:
list.cancelPage();
emitChange();
break;
case successAction:
list.receivePage(
action.response.result,
action.response.nextPageUrl
);
emitChange();
break;
}
};
}
var PaginatedStoreUtils = {
createListStore: createListStore,
createIndexedListStore: createIndexedListStore,
createListActionHandler: createListActionHandler
};
这是一个mixin,允许组件关注它们感兴趣的Stores,例如:mixins: [createStoreMixin(UserStore)]
。
function createStoreMixin(...stores) {
var StoreMixin = {
getInitialState() {
return this.getStateFromStores(this.props);
},
componentDidMount() {
stores.forEach(store =>
store.addChangeListener(this.handleStoresChanged)
);
this.setState(this.getStateFromStores(this.props));
},
componentWillUnmount() {
stores.forEach(store =>
store.removeChangeListener(this.handleStoresChanged)
);
},
handleStoresChanged() {
if (this.isMounted()) {
this.setState(this.getStateFromStores(this.props));
}
}
};
return StoreMixin;
}
{ follower: true, followed: false }
。getFolloweds()
和getFollowers()
方法将检索您需要显示在用户界面中的不同用户集合。 - fisherwebdev