Unable to read undefined property map in React

I have the following component that is called from a container component. The container component passes the transaction prop.

I know that the data property in prop is passed in order and has data and can be accessed from a console.log call. However, when I try to display the data and create a list, I get an error message:Cannot read property 'map' of undefined

Here's what the data looks like:

[
{"transid":3426,"acct":"acct1","category":"Auto"},
 {"transid":3427,"acct":"acct2","category":"Subscriptions"}
]

What am I doing wrong?

import React from 'react';


export default function TransactionManagerView (props) {

  console.log(props.data);

  return (
    <ul>
      {
        props.data.map(function(el,index) {
           return <li key={index}>{el.category}</li>
        })
      }
    </ul>
  )

}
+4
source share
2 answers

Provide validation for undefined prop.data, and then render the component, because it is possible that the attribute does not initially provide data, but is available in the second render. This should solve your problem.

class App extends React.Component {
  render() {
    var data = [
{"transid":3426,"acct":"acct1","category":"Auto"},
 {"transid":3427,"acct":"acct2","category":"Subscriptions"}
]
    return (
        <div ><TransactionManagerView data={data}/></div>
    )
  }

}



const TransactionManagerView = function(props) {

  console.log(props.data);

  return (
    <ul>
      {
        props.data && props.data.map(function(el,index) {
           return <li key={index}>{el.category}</li>
        })
      }
    </ul>
  )

}

ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
<div id="app"></div>
Run codeHide result
+6

, , . prop

import React from 'react';


export default function TransactionManagerView ({data = [], ...props}) {

  console.log(props.data);

  return (
    <ul>
      {
        data.map(function(el,index) {
           return <li key={index}>{el.category}</li>
        })
      }
    </ul>
  )

}
+1

Source: https://habr.com/ru/post/1666016/


All Articles