我想在react中呈现一个来自对象数组的元素列表。但是,它不能正常工作。
我丢失
export const PageBottomData = [
{
sectionName: "property1",
listOfLinks: [
{linkName: "value1", linkStatus: "inactive"},
{linkName: "value2", linkStatus: "inactive"},
]
},
{
sectionName: "property2",
listOfLinks: [
{linkName: "value1", linkStatus: "inactive"},
{linkName: "value2", linkStatus: "inactive"}
]
},
];
虽然数据已经正确导入(从控制台日志),但数据没有返回到呈现方法。我想呈现一个链接列表,其名称取自linkName属性。
App.js
import React from 'react';
import {PageBottomData} from './PageBottomData';
class App extends React.Component {
sectionListGroup = (keyword) => {
const listItems = PageBottomData.map(item => {
if(item.sectionName === keyword)
item.linkOfList.map((link, idx) => {
<li key = {idx} className = "list-group-item">link.linkName</li>
})
});
return listItems;
}
render() {
return (
<ul className = "list-group list-group-flush">
{sectionListGroup("Discover")}
</ul>
);
}
export default App;
错误:'sectionListGroup is undefined'
解决方案:
每个map
都需要return语句
const PageBottomData = [
{
sectionName: "property1",
listOfLinks: [
{ linkName: "value1", linkStatus: "inactive" },
{ linkName: "value2", linkStatus: "inactive" },
],
},
{
sectionName: "Discover",
listOfLinks: [
{ linkName: "value1 ", linkStatus: "inactive" },
{ linkName: "value2 ", linkStatus: "active" },
],
},
];
class App extends React.Component {
sectionListGroup = (keyword) => {
return PageBottomData.map((item) => {
if (item.sectionName === keyword)
return item.listOfLinks.map((link, idx) => {
return (
<li key={idx}>
{link.linkName} - {link.linkStatus}
</li>
);
});
});
};
render() {
return <ul>{this.sectionListGroup("Discover")}</ul>;
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
您的方法"sectionListGroup"中有一些小错误,我更新了方法并进行了更正。
sectionListGroup = (keyword) => {
const listItems = PageBottomData.map(item => {
if(item.sectionName === keyword)
{
return item.listOfLinks.map((link, idx) => {
return <li key = {idx} className = "list-group-item">{link.linkName}</li>
})
}
});
return listItems;
}
同样在测试示例中,您没有使用正确的参数(即{sectionListGroup("Discover")}
)正确调用方法。正如我们所看到的,您没有任何与"发现"值相关的数据,因此检查其他值,您将得到答案。