在Redux减速机期间,我的时刻正在改变

时间:2017-06-13 02:43:48

标签: reactjs redux react-redux momentjs

我从一个组件调用了一个调度函数(在event_actions.js中):

export function moveEvent( event, start) 
{  
    let startEv = event.start  // moment obj
    let endEv = event.end  // moment obj
    let diff = endEv.diff(startEv)  
    console.log("time diff", diff)  // time diff 7200000
    let newstart = moment(start, "YYYYMMDDHHmm")  
    console.log("newstart", newstart)  // newstart 2017-06-14T06:00:00-04:00 
    console.log("newend", newstart.add(diff, 'milliseconds').format()) // newend 2017-06-14T08:00:00-04:00
    let payload = {
        start: newstart,
        end: newstart.add(diff, 'milliseconds'),
        id: event.id,
    }      

    return { type: 'MOVE_EVENT', payload: payload }
}

这是我的' MOVE_EVENT'来自event_reducer.js的案例:

case 'MOVE_EVENT': {
    console.log("eventstart",action.payload.start.format())  // eventstart 2017-06-14T10:00:00-04:00
    console.log("eventend",action.payload.end.format())  //  eventend 2017-06-14T10:00:00-04:00
    console.log(state.events) // prints all events including the one I'm moving which already has the bad values for start and end

    let eventIndex = state.events.findIndex(event => event.id === action.payload.id)
    let newEvent = state.events[eventIndex]            
    newEvent.start = action.payload.start
    newEvent.end = action.payload.end

    return Object.assign( {}, 
        state, { 
            events: [
                ...state.events.slice(0, eventIndex), 
                newEvent,
                ...state.events.slice(eventIndex + 1),
            ] 
        }
    )
}

评论是console.logs正在打印的内容。从event_actions.js打印的日期是正确的。

我还注意到当我打印state.events时,坏值已经在我的状态。在我的案件甚至返回任何内容之前,如何才能更新我的州?

解答: 时刻(newstart).add(diff,'毫秒')

我仍然不确定我的状态在返回之前是如何变化的,但克隆了对象工作的时刻。

1 个答案:

答案 0 :(得分:1)

从你的代码:

  start: newstart,
  end: newstart.add(diff, 'milliseconds'),

add功能会更改日期:https://momentjs.com/docs/#/manipulating/add/

修复

在变异之前使用clonehttps://momentjs.com/docs/#/parsing/moment-clone/