从redux reducer中的对象复制原型函数

时间:2017-07-07 16:25:22

标签: javascript reactjs redux react-redux

void normalizeMinMaxAvg(double data[], int size,double& min, double& max, double& avg)
{
    if (size <= 0) //Nothing to do. Might want to add a return error code
        return;

    //0 is not a sensible value for init, what if all your values are negative?
    min = data[0];
    max = data[0];
    avg = 0;

    int sum = 0;

    for (i=0; i < size; i++)
    {
        sum += data[i];
        if ( data[i] > max) { //have to access your data by data[i]
            max=data[i]; //NOT i=max, you're assigning to max
        }

        if (data[i] < min) {
            min=data[i];
        }
    }
    avg = sum/size;
}

因此,当我的应用触发此操作时,它会为我的应用创建一个播放器对象。玩家对象上有原型方法(player.spawn(),player.killed()等),当我以这种方式复制它们时,那​​些不会被同化的。

1 个答案:

答案 0 :(得分:1)

{ ...someObject }对象扩展语法以及Object.assign方法仅复制对象自己的可枚举属性。不可复制的道具,原型道具和原型本身不会被复制。

因此,虽然这不是redux世界中的推荐做法,但您可以为域对象创建某种复制构造函数,例如:

class Player {
  constructor(anotherPlayer) {
    // copy the props of another player there
  }
}

并在减速器中使用它:

case "CONNECTOR_CONNECTION_FULFILLED":
   state = {
     ...state,
     appState: 'loggedIn',
   };
   state.ourPlayer = new Player(action.payload.player)

   break;