React-forEach()的结果未定义
2018-06-28
12165
我尝试从嵌套对象中渲染出 prop 值。我遇到了两个问题: 1. JSX 代码行(包含变量)未在浏览器中渲染 2. 控制台记录包含 .forEach() 方法的变量,返回“undefined”
问题:如何访问嵌套的 prop 值,将它们传递到 JSX 代码中,并在浏览器中渲染?
我的代码的当前状态:
//data object
project1: {
otherData: 'value',
technology: [
{
name: 'HTML',
logo: 'logoTest.png',
altText: 'HTML Logo'
},
{
name: 'CSS',
logo: 'CSSLogo.png',
altText: 'CSS Logo'
}
]},
project2: {
otherData: 'otherInfo',
technology: [
{
name: 'HTML',
logo: 'logoTest.png',
altText: 'HTML Logo'
},
{
name: 'CSS',
logo: 'CSSLogo.png',
altText: 'CSS Logo'
},
{
name: 'JavaScript',
logo: 'jsTest.png',
altText: 'JavaScript Logo'
}
]}
//Component
const Technology = props => {
const techList = props.technology; //object
console.log(techList); //logs: [{...},{name: 'CSS',logo: 'CSSLogo.png',altText:'CSS Logo'}]
let techItem = techList.forEach(function(arrayItem) {
let name = arrayItem.name;
let logo = arrayItem.logo;
let altText = arrayItem.altText;
console.log(name, logo, altText); //logs: CSS CSSLogo.png CSSLogo
let techDetails = [name, logo, altText];
console.log(techDetails); //logs values in separate console.logs: name, logo, altText
let loopThru = techDetails.forEach(function(item) {
console.log(item);
return item;
});
console.log(techItem,loopThru); //logs 'undefined, 'undefined'
});
return(
<div>
<p>Tech Component</p> //rendered in browser
<p>{loopThru}</p> // is NOT rendered in browser
</div>
);
};
1个回答
您的
loopThru
变量从未被分配任何内容,因为
forEach()
始终返回
undefined
。您可能打算使用
map()
,因为它实际上返回一个您可以渲染的数组。
来自 MDN :
forEach()
executes the callback function once for each array element; unlikemap()
orreduce()
it always returns the valueundefined
and is not chainable.
因此改为:
let loopThru = techDetails.map(function(item) {
console.log(item);
return item;
});
Chris
2018-06-28