【问题标题】:How to create a new instance of a model along with relations in redux-orm?如何在 redux-orm 中创建模型的新实例以及关系?
【发布时间】: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 });

但不是肯定的,这是正确的方法,如果它实际上正确链接,所以现在让问题悬而未决。

【问题讨论】:

    标签: reactjs redux redux-orm


    【解决方案1】:

    “手动”传递关系字段的相关 ID 值是一种方法。另一种是创建第一个模型,然后在创建期间或之后将第一个模型实例传递给第二个模型实例:

    const fred = User.create({name : "Fred"});
    
    // Pass during creation
    const pet = Pet.create({name : "Spot", user : fred});
    
    // Or after creation
    const pet = Pet.create({name : "Spot"});
    pet.user = fred;
    
    // Then ask Redux-ORM to apply queued updates and return the updated data
    return session.reduce();
    

    编辑

    更新:作为a series on "Practical Redux" 的前两部分,我在 Redux-ORM 上发表了几篇文章,讨论了我从自己使用 Redux 的经验中开发的技术。

    【讨论】:

    • 太好了,成功了。我想我被创作后没有准备好的关系所困扰(即const pet = Pet.create({}); typeof pet.user === 'undefined')。我习惯了 Eloquent (laravels orm),所以只是假设它有效。旁注,使用 redux-orm + 草稿/查看/编辑模式(根据您的建议)为我的反应草稿问题添加了一个评论,并附上了一个示例 repo(基于您的建议)谢谢!
    猜你喜欢
    • 2018-08-06
    • 2019-03-10
    • 2011-01-29
    • 1970-01-01
    • 2023-02-11
    • 2011-01-03
    • 2013-11-06
    • 1970-01-01
    • 2019-03-25
    相关资源
    最近更新 更多