数组中的Redux项目已更新其ID

时间:2017-11-15 05:50:58

标签: javascript react-native redux expo

我正在开发一个本机(本地)事件应用程序,我遇到了一个问题,我的模拟事件的ID会被更新,因为他们不应该只是在#39 ;重新整数,当id是字符串时我没有这个问题。

基本流程是我显示事件列表,当用户按下该事件时,他们将被带到该事件视图。我通过使用 eventInFocus 事件* reducers并在** eventView 容器中查找我需要的事件来完成此操作。

当我按下某个特定事件时,所有事件ID都会更新并且难以调试,因为它声明前一个状态已经有混合ID,这非常令人困惑,因为渲染项目中没有任何问题主视图(循环遍历数组,使用id作为键)。 如果我选择第一个事件,我会收到一个错误,即无法找到该事件,如果我选择其他2个事件中的任何一个,则会随机更新事件ID。

事件减少器

const defaultEvents = [{
    id: 0,
    name: 'my birthday',
    date: new Date(),
    repeatAnnually: false,
    wallPaperSource: null
  },{
    id: 1,
    name: 'yosemite trip',
    date:  new Date(),
    repeatAnnually: true,
    wallPaperSource: null
  }, {
   id: 2,
   name: 'trip to dublin',
   date: new Date(),
   repeatAnnually: false,
   wallPaperSource: null
}];

const event = (state, action) => {
  switch (action.type) {
    case EVENT_EDITED:
      if(state.id !== action.event.id){
        return state;
      }
      return action.event;
    default:
      return state;
  }
}

function events(state = defaultEvents, action){
  switch(action.type){
    case ADD_EVENT:
      return [
        ...state,
        {
          id: action.event.id,
          name: action.event.name,
          date: action.event.date,
          repeatAnnually: action.event.repeatAnnually,
          wallPaperSource: action.event.wallPaperSource || null
        }];
    case EVENT_EDITED:
      return state.map(e =>
        event(e, action)
      )
    default:
      return state;
  }
}

eventInFocus reducer

function eventInFocus(state = {}, action){
  switch(action.type){
    case "UPDATE_EVENT_IN_FOCUS":
      return Object.assign({}, state, action.event);
    case VIEW_EVENT:
      return Object.assign({}, action.event);
    default:
      return state;
  }
}

eventContainer - 列表中每个项目周围的容器(主视图)

const mapStateToProps = (state, ownProps) => {
  return {
    ownProps
  }
}

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    onPress: (event)=> {
      dispatch(viewEvent(event));
    }
  }
}

viewEventContainer - 适用于单个事件视图

const mapStateToProps = (state, ownProps) => {
  const {events, eventInFocus } = state;
  viewEvent = find(events, e => e.id = eventInFocus.id);
  return {
    event: viewEvent,
    ownProps
  }
}

const mapDispatchToProps = (dispatch, state) => {
  return {
    onEditEvent: (event) => {
      dispatch(editEvent(event));
    }
  }
}

const EventViewContainer = connect(
  mapStateToProps,
  mapDispatchToProps
)(EventView);

viewEvent action

export const viewEvent = (event) => {
  return {
    type: VIEW_EVENT,
    event
  }
}

对于redux,我有什么遗漏吗?我的减速机结构不合理吗?令我困惑的部分是为什么它只发生整数而不是字符串。提前谢谢!

当我按下某个事件时说明,因为您可以看到之前的状态已经有事件的变异ID

1 个答案:

答案 0 :(得分:1)

以下是代码中包含错误的行:

viewEvent = find(events, e => e.id = eventInFocus.id);
                                   ^
                                   here 

正如您所看到的,state每次调用mapStateToProps时都会发生变异。