简体   繁体   English

如何修复错误类型错误:无法读取未定义的属性“地图”

[英]How to fix the error TypeError: Cannot read property 'map' of undefined

The error is given in my map function.错误在我的地图函数中给出。

I'm following a reactjs tutorial, and I keep running into an issue when passing the value from the state of one component into another component.我正在关注reactjs教程,并且在将值从一个组件的状态传递到另一个组件时一直遇到问题。 I am connecting to back end with axios.get() .我正在使用axios.get()连接到后端。

export default class Viewcustomer extends React.Component{

  constructor(props) {
    super(props)

    this.state = {
      Id:"",
      name:"",
      fax:"",    
      NIC: "",
      type: "",
      email: "",
      website: "",
      address: "",
      phoneNo: "",
      DOB: "",
      note: "",
      customer:[]  
    }    
  }

  onChange = (e) => {
    this.setState({[e.target.name]: e.target.value})
  }

  componentDidMount() {
    axios.get(`http://localhost:5001/customer/view`)
      .then(res => {
         const customers = res.data;
         this.setState({ customers });
      })
  }

  render(){
    return(
      <table width="100%">
        <tr>
          <th>Id</th>
          <th>name</th>
          <th>fax</th>
          <th>NIC</th>
          <th>type</th>
          <th>email</th>
          <th>address</th>
          <th>phoneNo</th>
          <th>DOB</th>
          <th>note</th>

        </tr>
        //Error raised by this line of code
        { this.state.customers.map(customer =>
          <tr>
            <td>{customer.Id}</td>
            <td>{customer.name}</td>
            <td>{customer.fax}</td>
            <td>{customer.NIC}</td>
            <td>{customer.type}</td>
            <td>{customer.email}</td>
            <td>{customer.address}</td>
            <td>{customer.phoneNo}</td>
            <td>{customer.DOB}</td>
            <td>{customer.note}</td>
          </tr>)}
      </table>
    )
  }
}

Image of the error message错误消息的图像

Edit编辑

Error relates to the line marked with the quote, issue raised by the map() function, however the underlying issue is the this.state.customers is undefined .错误与标有引号的行有关,由 map() 函数引发的问题,但是潜在的问题是this.state.customersundefined

this.state.customers.map(...

The problem is that this.state.customers is set when the component mounts, and only after an asynchronous call with axios returns.问题是this.state.customers是在组件挂载时设置的,只有在 axios 异步调用返回后才设置。 That means that when the component is first rendered, this.state.customers will not have been set yet.这意味着当组件第一次被渲染时, this.state.customers还没有被设置。

Posible solution可能的解决方案

Either check if this.state.customers exists before using it, or maybe just initialize it as an empty array.在使用之前检查this.state.customers存在,或者只是将其初始化为一个空数组。 I noticed that you're initializing a customer (singular) as an empty array, is that a typo?我注意到您将customer (单数)初始化为一个空数组,这是一个错字吗?

constructor(props) {
    super(props)

    this.state = {
        Id:"",
        name:"",
        fax:"",    
        NIC: "",
        type: "",
        email: "",
        website: "",
        address: "",
        phoneNo: "",
        DOB: "",
        note: "",
        customers:[] // initialize customers, this.state.customers is now defined
    }
}

The first thing you should know is that componentDidMount runs after render method.您应该知道的第一件事是componentDidMount在 render 方法之后运行。 So in the first render your customer parameter is still [] and even you write a simple console.log() in componentDidMount it runs after render method.因此,在第一次渲染中,您的customer参数仍然是[] ,即使您在componentDidMount编写了一个简单的console.log()它也会在渲染方法之后运行。

You can understand what is happening by running the code below:您可以通过运行以下代码了解正在发生的事情:

    class Test extends React.Component {
        constructor(props){
           console.log('constructor')
        }
        render(){
          console.log('render')
        }
        componentDidMount(){
          console.log('componentDidMount')
        }
    }

The result will be like this:结果将是这样的:

constructor构造函数

render使成为

componentDidMount组件DidMount

But for solving your problem you should show a spinner or something like this in the time that you are waiting to receive your response from axios.但是为了解决您的问题,您应该在等待从 axios 接收响应的时候展示一个微调器或类似的东西。 and your component could be like this:你的组件可能是这样的:

export default class Viewcustomer extends React.Component{

  constructor(props) {
    super(props)

    this.state = {
      Id:"",
      name:"",
      fax:"",    
      NIC: "",
      type: "",
      email: "",
      website: "",
      address: "",
      phoneNo: "",
      DOB: "",
      note: "",
      customer:[]  
    }    
  }

  onChange = (e) => {
    this.setState({[e.target.name]: e.target.value})
  }

  componentDidMount() {
    axios.get(`http://localhost:5001/customer/view`)
      .then(res => {
         const customers = res.data;
         this.setState({ customers });
      })
  }

  render(){
    if(this.state.customers.length===0){
    return(
     <div>Loading...</div>
    )
    }
    else{
    return(
      <table width="100%">
        <tr>
          <th>Id</th>
          <th>name</th>
          <th>fax</th>
          <th>NIC</th>
          <th>type</th>
          <th>email</th>
          <th>address</th>
          <th>phoneNo</th>
          <th>DOB</th>
          <th>note</th>

        </tr>
        //Error raised by this line of code
        { this.state.customers.map(customer =>
          <tr>
            <td>{customer.Id}</td>
            <td>{customer.name}</td>
            <td>{customer.fax}</td>
            <td>{customer.NIC}</td>
            <td>{customer.type}</td>
            <td>{customer.email}</td>
            <td>{customer.address}</td>
            <td>{customer.phoneNo}</td>
            <td>{customer.DOB}</td>
            <td>{customer.note}</td>
          </tr>)}
      </table>
    )
    }
  }
}

Please vote me up if it was helpful:)如果有帮助,请投票给我:)

Your problem is that in the usage you're using this.state.costumers and your define state is customer .您的问题是,在您使用this.state.costumers的用法中,您的定义状态是customer

export default class Viewcustomer extends React.Component {
    constructor(props) {
        super(props)

        this.state = {
            Id: "",
            name: "",
            fax: "",
            NIC: "",
            type: "",
            email: "",
            website: "",
            address: "",
            phoneNo: "",
            DOB: "",
            note: "",
            customers: []


        }

    }

    onChange = (e) => {
        this.setState(
            { [e.target.name]: e.target.value }
        )
    }
    componentDidMount() {
        axios.get(`http://localhost:5001/customer/view`)
            .then(res => {
                const customers = res.data;
                this.setState({ customers });
            })
    }


    render() {
        const { costumers } = this.state:
        return (
            <table width="100%">
                <tr>
                    <th>Id</th>
                    <th>name</th>
                    <th>fax</th>
                    <th>NIC</th>
                    <th>type</th>
                    <th>email</th>
                    <th>address</th>
                    <th>phoneNo</th>
                    <th>DOB</th>
                    <th>note</th>

                </tr>
                {customers.map(customer =>
                    <tr>
                        <td>{customer.Id}</td>
                        <td>{customer.name}</td>
                        <td>{customer.fax}</td>
                        <td>{customer.NIC}</td>
                        <td>{customer.type}</td>
                        <td>{customer.email}</td>
                        <td>{customer.address}</td>
                        <td>{customer.phoneNo}</td>
                        <td>{customer.DOB}</td>

                        <td>{customer.note}</td>
                    </tr>)}
            </table>


        )
    }
}

That's the whole problem because when you initialize the costumers state as an empty Array, the map method will stop failing.这就是整个问题,因为当您将costumers状态初始化为空数组时, map方法将停止失败。 Hope this helps.希望这可以帮助。 Best Regards.此致。

As noted in other answers this.state.customers is undefined throwing the error.正如其他答案中所述, this.state.customersundefined抛出错误。 This is because initially in the constructor you are initialising customer singular and not customers , quick change should fix this.这是因为最初在构造函数中您初始化的是customer单数而不是customers ,快速更改应该可以解决这个问题。

Can I recommend since you are looking at tutorials, React Hooks are a really powerful and intuitive way of using "stateless" (they do still hold a state) functional components instead of class components.我可以推荐,因为您正在查看教程, React Hooks是一种使用“无状态”(它们仍然保持状态)功能组件而不是类组件的非常强大且直观的方式。 They simplify the coding of components massively and make handling state far easier.它们极大地简化了组件的编码并使处理状态变得更加容易。

暂无
暂无

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

相关问题 如何修复JavaScript中的“ TypeError:无法读取未定义的属性&#39;map&#39;”? - How to fix “TypeError: Cannot read property 'map' of undefined” in JavaScript? 类型错误:无法读取未定义的属性“地图”……如何修复它 - TypeError: Cannot read property 'map' of undefined…How to fix it 如何修复错误“错误类型错误:无法读取未定义的属性‘0’” - how to fix the error "ERROR TypeError: Cannot read property '0' of undefined" 如何修复“Uncaught TypeError: Cannot read property 'scrollHeight' of undefined”错误 - how to fix “Uncaught TypeError: Cannot read property 'scrollHeight' of undefined” error 如何修复“未捕获的类型错误:无法读取未定义的属性‘替换’”错误? - How to fix "Uncaught TypeError: Cannot read property 'replace' of undefined" error? 如何修复“TypeError:无法读取未定义的属性 'id'”错误? - How to fix “TypeError: Cannot read property 'id' of undefined” error? TypeError:无法读取未定义的属性“地图”错误 - TypeError: Cannot read property 'map' of undefined" error 如何修复 TypeError:无法读取未定义的属性? - How to fix TypeError: Cannot read property of undefined? 如何修复“未捕获的类型错误:无法读取未定义的属性‘地图’”? - How do I fix "Uncaught TypeError: Cannot read property 'map' of undefined"? 我该如何修复TypeError:无法读取未定义REACT的属性“ map” - How can i fix TypeError: Cannot read property 'map' of undefined REACT
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM