为什么会出现TypeError:无法读取undefined属性'completed'?

时间:2017-06-18 12:50:09

标签: javascript reactjs react-redux

我为todo reactjs app开发了一个减速器。这是减速器的一部分:

 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 个答案:

答案 0 :(得分: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时,它会抛出。

详见:

相关问题