无法读取 React 中未定义的属性“地图" [英] Cannot read property 'map' of undefined in React
问题描述
我有从容器组件调用的以下组件.容器组件传递事务属性.
我知道 prop 中的 data 属性被很好地传递并且有数据并且可以从 console.log 调用访问.但是,当我尝试映射数据并创建列表时,出现错误:Cannot read property 'map' of undefined
数据如下:
<预><代码>[{"transid":3426,"acct":"acct1","category":"Auto"},{"transid":3427,"acct":"acct2","category":"订阅"}]我做错了什么?
从'react'导入React;导出默认函数 TransactionManagerView(道具){控制台日志(道具.数据);返回 (<ul>{props.data.map(function(el,index) {return {el.category} })})}
检查未定义的 prop.data
然后渲染组件,因为 props 最初可能不提供数据,但在第二个渲染中可用.那应该可以解决您的问题
class App extends React.Component {使成为() {变量数据 = [{"transid":3426,"acct":"acct1","category":"Auto"},{"transid":3427,"acct":"acct2","category":"订阅"}]返回 (<div ><TransactionManagerView data={data}/></div>)}}const TransactionManagerView = 函数(道具){控制台日志(道具.数据);返回 (<ul>{props.data &&props.data.map(function(el,index) {return {el.category} })})}ReactDOM.render( , 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>
I have the following component which is being called from a container component. The container component passes the transactions prop.
I know that the data property in prop is being passed in fine and has data and can be accessed from the console.log call. However, when I try to map the data and create the list, I get an error: Cannot read property 'map' of undefined
Here is 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>
)
}
Provide a check for undefined prop.data
and then render the component because it is possible that the props initially don't provide the data but is available in the second render. That 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>
这篇关于无法读取 React 中未定义的属性“地图"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!