【问题标题】:Cannot read property 'map' of undefined in React无法读取 React 中未定义的属性“映射”
【发布时间】:2017-05-21 10:37:01
【问题描述】:

我有以下从容器组件中调用的组件。容器组件传递 transactions 属性。

我知道 prop 中的 data 属性被很好地传递并且有数据并且可以从 console.log 调用中访问。但是,当我尝试映射数据并创建列表时,出现错误:Cannot read property 'map' of undefined

数据如下所示:

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

我做错了什么?

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

}

【问题讨论】:

  • 你可以使用 console.log 道具吗?您如何使用 TransactionManagerView?
  • 是的。 Console.log(props) 返回所有的道具,一切都很好。我只是从一个将数据作为道具传递的同名容器组件中调用此组件。
  • 这对我有用:jsfiddle.net/69z2wepo/66919
  • 好的。调用它时,我必须在其他地方有什么东西。我再看看。

标签: reactjs


【解决方案1】:

检查未定义的prop.data,然后渲染组件,因为道具最初可能不提供数据,但在第二次渲染中可用。那应该可以解决您的问题

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>

【讨论】:

    【解决方案2】:

    这是因为组件的渲染发生在组件接收到数组之前。作为一个选项,您可以设置道具的默认值

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

    【讨论】:

      猜你喜欢
      • 2018-01-07
      • 2016-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-26
      • 2021-03-01
      • 2021-08-12
      相关资源
      最近更新 更多