2017-02-06 19 views
0

我正在使用經典的來做列表項目學習Redux,我遇到了一個奇怪的問題。使用特定的縮小器/動作後,陣列中的對象變爲undefined

基本上,我有一個帶有複選框的待辦事項列表,當用戶點擊一個複選框時,將調度一個操作,該操作應將該對象的完成屬性標記爲true並且組件應該更新。

但是...當這個動作火災,這是應該被成功標記爲完成目標與它的所有屬性,則返回,但待辦事項列表的其餘部分(數組中的其他對象)遭到損壞,失去所有他們的屬性和他們變成'未定義',從而導致渲染問題。

我試圖包括所有我認爲是相關的代碼,但我認爲我在減速器中做了錯誤的事情,但我找不到找到問題。

待辦事項列表組件

class TodoList extends Component { 

    render(){ 
     const {todos, showCompleted, searchTerm} = this.props; 
     const renderTodos =() => { 
      if (todos.length === 0) { 
       return (
        <p className="container__message">Nothing to do.</p> 
       ); 
      } 
      return TodoAPI.filterTodos(todos, showCompleted, searchTerm).map((todo) => { 
       return (
        <Todo key={todo.id} {...todo}/> 
       ); 
      }); 
     }; 
     return (
      <div> 
       {renderTodos()} 
      </div> 
     ); 
    } 
} 
export default connect((state) => { 
    return state; 
})(TodoList); 

藤組件

class Todo extends Component { 

    render() { 
     const {id, text, completed, createdAt, completedAt, dispatch} = this.props; 
     const todoClass = completed 
      ? 'todo todo-completed' 
      : 'todo'; 

     const renderDate =() => { 
      let displayMessage = 'Created '; 
      let timestamp = createdAt; 

      if (completed) { 
       displayMessage = 'Completed '; 
       timestamp = completedAt; 
      } 
      return displayMessage + moment.unix(timestamp).format('MMM Do YYYY @ h:mm a'); 
     }; 

     return (
      <div className={todoClass} 
       onClick={event => dispatch(actions.toggleTodo(id)) }> 
       <input type="checkbox" checked={completed} readOnly/> 
       <div> 
        <p>{text}</p> 
        <p className="todo__subtext">{renderDate()}</p> 
       </div> 
      </div> 
     ); 
    } 
} 
export default connect()(Todo); 

行動

export const toggleTodo = (id) => { 
    return { 
     type: 'TOGGLE_TODO', 
     id: id 
    }; 
}; 

減速

export const todosReducer = (state = [], action) => { 
    switch (action.type) { 
    case 'TOGGLE_TODO': 
     return state.map((todo) => { 
      if (todo.id === action.id) { 
       let nextCompleted = !todo.completed; 

       return { 
        ...todo, 
        completed: nextCompleted, 
        completedAt: todo.completed ? moment().unix() : 0 
       }; 
      } 
     }); 
    default: 
     return state; 
    } 
}; 

回答

2

問題是你是不是returning任何東西,如果condition todo.id === action.id失敗。隨着如果你不return什麼,默認情況下它會returnundefinedmap,試試這個:

return state.map((todo) => { 
    if (todo.id === action.id) { 
     let nextCompleted = !todo.completed; 

     return { 
      ...todo, 
      completed: nextCompleted, 
      completedAt: todo.completed ? moment().unix() : 0 
     }; 
    }else{ 
     return todo; 
    } 
}); 

檢查:

a=[1,2,3,4,5,6]; 
 
b = a.map (i => { if(i % 2 == 0) return i;}) 
 
console.log(b);

+0

這也解釋了! else語句完全解決了這個問題,我明白爲什麼感謝你的答案。 – cinnaroll45

+0

當然,我正在等待時限到期。 – cinnaroll45