【发布时间】:2017-03-12 14:43:48
【问题描述】:
在使用redux-orm时,如何在创建模型实例的过程中添加相关数据?
例如给定以下两种模型:
// User
import {fk, many, Model} from 'redux-orm';
export default class User extends Model {
static modelName = 'User';
static fields = {
pets: many('Pet', 'pets'),
};
}
// Pet
import {fk, many, Model} from 'redux-orm';
export default class Pet extends Model {
static modelName = 'Pet';
static fields = {
user: fk('User', 'pets'),
};
}
我在宠物模型中的创建减速器看起来像:
case 'PET/CREATE':
const newPet = Pet.create(action.payload);
newPet.user.add(action.parentId); // parentId is the user id
break;
但这会导致错误,因为 newPet.user 未定义。我也试过withRefs
case 'PET/CREATE':
const newPet = Pet.create(action.payload).withRefs;
newPet.user.add(action.parentId);
break;
我也尝试过重新查找 id:
case 'PET/CREATE':
const newPet = Pet.create(action.payload);
// console.log(newPet.id); // correctly outputs id
Pet.withId(newPet.id).user.add(action.parentId);
break;
编辑
发现我能做到
const newPet = Pet.create({ ...action.payload, user: action.parentId });
但不是肯定的,这是正确的方法,如果它实际上正确链接,所以现在让问题悬而未决。
【问题讨论】: