【问题标题】:How to fix the error TypeError: Cannot read property 'map' of undefined如何修复错误 TypeError: Cannot read property 'map' of undefined
【发布时间】:2020-05-02 04:03:38
【问题描述】:

我的地图函数中给出了错误。

我正在关注reactjs 教程,当将值从一个组件的状态传递到另一个组件时,我一直遇到问题。 我正在使用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

编辑

错误与标有引号的行有关,由 map() 函数引发,但根本问题是 this.state.customersundefined

【问题讨论】:

标签: javascript reactjs


【解决方案1】:
this.state.customers.map(...

问题是this.state.customers是在组件挂载时设置的,并且只有在使用axios异步调用返回之后。这意味着当组件第一次渲染时,this.state.customers 还没有设置。

可能的解决方案

在使用之前检查this.state.customers 是否存在,或者只是将其初始化为一个空数组。我注意到您正在将 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
    }
}

【讨论】:

    【解决方案2】:

    你应该知道的第一件事是componentDidMount 在渲染方法之后运行。因此,在第一次渲染中,您的 customer 参数仍然是 [],即使您在 componentDidMount 中编写了一个简单的 console.log(),它也会在渲染方法之后运行。

    你可以通过运行下面的代码来了解发生了什么:

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

    结果会是这样的:

    构造函数

    渲染

    componentDidMount

    但是为了解决您的问题,您应该在等待收到来自 axios 的回复时显示一个微调器或类似的东西。你的组件可能是这样的:

    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>
        )
        }
      }
    }
    

    如果对我有帮助,请投票给我:)

    【讨论】:

      【解决方案3】:

      您的问题是在使用中您使用的是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>
      
      
              )
          }
      }
      

      这就是整个问题,因为当您将costumers 状态初始化为一个空数组时,map 方法将停止失败。希望这可以帮助。最好的祝福。

      【讨论】:

      • 谢谢它有助于修复。谢谢你的解释。
      • 如果我的回答对你有帮助,你能投票给我吗?问候。 @ChehaniLakshika
      【解决方案4】:

      如其他答案中所述,this.state.customersundefined 引发错误。这是因为最初在构造函数中初始化customer 奇异而不是customers,快速更改应该可以解决这个问题。

      我可以推荐,因为您正在查看教程,React Hooks 是使用“无状态”(它们仍然保持状态)功能组件而不是类组件的一种非常强大且直观的方式。它们极大地简化了组件的编码并使处理状态变得更加容易。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-02-22
        • 2020-01-21
        • 2021-06-25
        • 2021-10-31
        • 1970-01-01
        • 2017-04-24
        • 2023-03-15
        • 1970-01-01
        相关资源
        最近更新 更多