2017-06-18 52 views
0

我開發了todo reactjs應用程序的reducer。這是減速機的一部分:爲什麼會出現TypeError:無法讀取未完成的屬性undefined?

case "SHOWCOMPLETE": 
      //todo remove 
      debugger; 
      return state.map(todo => { 
       if (todo.completed) { 
        return todo 
       } 
       else 
       {} 
      }) 

這是顯示已完成的待辦事項:true。然而,todos組件將這個錯誤渲染出來。這是組件的一部分:

if (this.props.todos) { 
      //todo remove 
      console.log('testing=this.props', this.props); 
      display = this.props.todos.map 
      (
        (todo) => (

         <p className={todo.completed ? 'strikethrough' : ''} 
          onClick={() => this.complete(todo.name)}> {todo.name}!</p> 
        ) 

      ) 
     } 

爲什麼我得到這個錯誤?這裏是一個github鏈接:github

回答

1

你實際上想要做的是使用filter而不是map。當您使用map你:

let a = [1,2,3].map(n=> {if (n !== 2) return n}) 
 

 
console.log('a = ', a); //result = [1, undefined, 3];

filter會給你:

let a = [1,2,3].filter(n=> (n !== 2)); 
 

 
console.log('a = ', a); //result = [1, 3]

undefined在使用map作爲傳遞你待辦事項,然後訪問todo.completed它拋出。

多見於:

相關問題