简体   繁体   English

React---TypeError:无法读取未定义的属性“地图”

[英]React---TypeError: Cannot read property 'map' of undefined

I'm following the react.js tutorial, and I keep running into this error 'Cannot read property 'map' of undefined' when the Tasks component is executed.我正在关注 react.js 教程,在执行任务组件时,我一直遇到此错误“无法读取未定义的属性 'map'”。 What would cause this error?什么会导致这个错误? Tasks component任务组件

import React, { Component } from 'react';
import Task from './Task';

class Tasks extends Component{
    render() {
        return this.props.tasks.map(task => <Task task={task} key={task.id} />); 
    }
}

export default Tasks;

Task component任务组件

import React, { Component } from 'react';

class Task extends Component {
    render(){
        const { task } = this.props;

        return <div>
           {task.title} - 
           {task.description} - 
           {task.done} - 
           {task.id}
            <input type="checkbox"/>
            <button>x</button>
        </div>
    }

}

export default Task;

Thank you very much.非常感谢。

This is a common issue, and in your case is caused by render being called before the prop has any data.这是一个常见问题,在您的情况下是由于在道具有任何数据之前调用render引起的。 The simplest fix is to check your prop and only render when it is defined:最简单的解决方法是检查您的道具并仅在定义时渲染:

class Tasks extends Component{
    render() {
        return Array.isArray(this.props.task) && this.props.tasks.map(task => <Task task={task} key={task.id} />); 
    }
}

This error 'Cannot read property 'map'' means that you trying to map a variable that is undefined, in your case, the variable tasks .此错误'Cannot read property 'map''意味着您尝试 map 未定义的变量,在您的情况下为变量tasks Example:例子:

 // OK let props = { tasks: ['a', 'b', 'c'] } props.tasks.map(task => console.log(task)); // a, b, c // Undefined let props2 = {}; props2.tasks.map(task => console.log(task)); // Throw an error

In the first example, you have defined the variable tasks , so the map works.在第一个示例中,您已经定义了变量tasks ,因此 map 可以工作。

In the second example, tasks is not defined, so when you try to map , this throw an error.在第二个示例中,未定义tasks ,因此当您尝试map时,会引发错误。

To overcome this, verify if the variable exists, before use the map :为了克服这个问题,在使用map之前验证变量是否存在:

 let props = {}; // Using ternary operator props.tasks? props.tasks.map(task => console.log(task)): console.log('Ok'); // Ok // Using if if (props.tasks) { props.tasks.map(task => console.log(task)); } else { console.log('Ok'); }

Easy Solution简单的解决方案

1. comment the line with the.map function, save the file, and reload the page 1.注释 .map function 行,保存文件,重新加载页面

2. uncomment the line and do not reload the browser. 2.取消注释该行并且不要重新加载浏览器。

NOTE: You will have to repeat these procedures anytime you reload the browser.注意:每次重新加载浏览器时,您都必须重复这些过程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM