0
我有一個應用程序與許多實體從API請求。 我想添加一個通用的方式來獲取任何實體,因爲這樣我不需要創建數百個文件,我也可以創建一些通用組件(例如顯示實體值的表) 最佳實踐是什麼在redux中這樣做,或者也許有一些npm包。 要清楚,我將介紹我是如何在不斷變化做到了:Redux通用還原器
我一般商店:
var Api = require('../utils/api');
var Reflux = require('reflux');
var Actions = require('../actions');
module.exports = Reflux.createStore({
listenables: [Actions],
getEntities: function (entityName) {
var url = "api/generic/" + entityName;
return Api.get(url)
.then(function (json) {
this.triggerChange(entityName, json);
}.bind(this));
},
triggerChange: function (entityName, json) {
this.trigger('change', {entity: entityName, value: json});
},
updateEntity: function (body, entityName) {
var url = "api/generic/" + entityName + "/edit";
return Api.post(url, body)
.then(function (json) {
this.getEntities(entityName);
}.bind(this)).catch(this.getEntities(entityName));
},
deleteEntity: function (id, entityName) {
var url = "api/generic/" + entityName + "/" + id;
return Api.delete(url)
.then(function (json) {
this.getEntities(entityName);
}.bind(this)).catch(this.getEntities(entityName));
}
});
And my listener:
onChangeEntities: function (event, result) {
if (event == "change"){
var entityName = result.entity;
var setState = this.setState;
var dataContext = this.state.dataContext;
var arr = [];
dataContext.map(function (element) {
arr.push(element);
});
var state = this.state;
Entities.map(function (entity) {
if (entity.name == entityName)
{
if (dataContext.filter(function (entity) {
return entity.entityName && entity.entityName == entityName;
}).length == 0)
{
arr.push({entityName: entityName, value: result.value});
}
else{
var entity = dataContext.filter(function (entity) {
return entity.name && entity.name == entityName;
})[0];
var keys = Object.keys(dataContext);
keys.map(function (key) {
if (dataContext[key].entityName == entityName)
{
arr.splice(key, 1);
}
});
arr.push({entityName: entityName, value: result.value});
}
}
});
this.setState({dataContext: arr});
}