在Redux中克隆然后变异方法 [英] Clone and then mutate approach in redux

查看:85
本文介绍了在Redux中克隆然后变异方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一段时间以来,我一直在阅读redux上的内容.对我来说,有一件奇怪的事.在大多数人给出的示例中,所有复制逻辑都是通过reducer处理的. 我正在使用打字稿,并希望采用一种基于类的方法.但是也许我想念一些东西.

I've been reading stuff on redux for a while. And there is a strange thing for me. In most examples people give, all the copying logic is handled via reducers. I'm using typescript and want to adopt a more class-based approach. But maybe I'm missing something.

假设我有一个购物车课程.以及小车减速器和小车动作. 看起来是这样的:

Let's say I have a shopping Cart class. Along with cart reducer and cart actions. It looks the following way:

export class Cart
{
    private items:{[key:string]:number} = {};

    constructor(items:{[key:string]:number} = {})
    {
        Object.assign(this.items, items);
    }

    public addItem(id:string)
    {
        this.items[id] = this.items[id]?this.items[id]+1:1;
    }

    public removeItem(id:string)
    {
        this.items[id]--;

        if(this.items[id] <= 0)
        {
            delete this.items[id];
        }

    }

    public setItemsCount(id:string, count:number)
    {
        this.items[id] = count;
    }

    public clone():Cart
    {
        return new Cart(Object.assign({}, this.items));
    }

}

所以,这里我将克隆逻辑封装在一个类中.

So, here I'm incapsulating cloning logic in a class.

在我的减速器中,我要签名:

And in my reducer I would go with the signature:

function reducer(state = new Cart(), action:Action): Cart {
    //first clone, then mutate, then return
}

或者,实际上,如何简单地通过通用方法对对象进行深克隆,然后对其进行变异然后返回呢?这种方法有什么不好?

Or, actually, how about simply deep-cloning objects via a universal method, then mutating them and then returning? What's bad about that approach?

推荐答案

出于多种原因,这被认为是不好的做法.

This is considered bad practice for several reasons.

首先,不鼓励将类实例保持在状态中因为它将中断时间旅行调试.您可以做到这一点,但这不是正确"的方法.

First, keeping class instances in state is discouraged because it will break time-travel debugging. You can do it, but it's not the "right" way.

第二,您的班级正在直接对其内容进行变异.这也将中断时间旅行调试,并且导致已连接React组件无法正确重新渲染.

Second, your class is directly mutating its contents. This will also break time-travel debugging, and result in your connected React components not re-rendering properly.

第三,Redux鼓励采用更具功能性的方法,而不是OOP.

Third, Redux encourages a more functional approach, not OOP.

您可能想通读我最近的两篇博客文章, Redux之道,第1部分-实现和意图

You may want to read through my two recent blog posts, The Tao of Redux, Part 1 - Implementation and Intent and The Tao of Redux, Part 2 - Practice and Philosophy, which go into detail on what technical limitations Redux requires and why, why common practices exist for using Redux, and why other approaches may be possible but are not considered idiomatic.

这篇关于在Redux中克隆然后变异方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆