所以我的代码是:
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
myArray: [
{id:1, continent:[
{id:1, name: 'Russia'},
{id:2, name: 'Germany'},
{id:3, name: 'Poland'}
]},
{id:2, continent:[
{id:1, name: 'China'},
{id:2, name: 'India'},
{id:3, name: 'Bangladesh'}
]},
{id:3, continent:[
{id:1, name: 'Brazil'},
{id:2, name: 'Peru'},
{id:3, name: 'Chile'}
]}
],
otherValue: 23
}
}
subBoardList(id){
return this.state.myArray[id].map((continent) => {
return(
<View>
<Text>{continent.name}</Text>
</View>
)
})
}
render() {
return (
{this.subBoardList(2)}
);
}
}
我想显示其id传递给subBoardList
函数的continental数组的内容。我该怎么办?
错误:
TypeError: undefined is not an object (evaluating 'this.state.myArray[id].map')
答案 0 :(得分:5)
您应该使用:
this.state.myArray[id].continent.map(...
答案 1 :(得分:0)
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
myArray: [
{id:1, continent:[
{id:1, name: 'Russia'},
{id:2, name: 'Germany'},
{id:3, name: 'Poland'}
]},
{id:2, continent:[
{id:1, name: 'China'},
{id:2, name: 'India'},
{id:3, name: 'Bangladesh'}
]},
{id:3, continent:[
{id:1, name: 'Brazil'},
{id:2, name: 'Peru'},
{id:3, name: 'Chile'}
]}
],
otherValue: 23
}
}
subBoardList(id){
return this.state.myArray[id].continent.map((continent) => {
// You need to add continent key after myArray since
// index 2 = {id:3, continent:[
// {id:1, name: 'Brazil'},
// {id:2, name: 'Peru'},
// {id:3, name: 'Chile'}
//]}
return(
<View>
<Text>{continent.name}</Text>
</View>
)
})
}
render() {
return (
<div> {this.subBoardList(2)} </div>
// Add a div after return it's import to render anything
);
}
}
尝试这样。
答案 2 :(得分:0)
如果您要按id搜索并且id不能作为索引,例如,id可以是任何数字(10,11,12或120,155,254 ...),则您的subBoardList
应该像这样
subBoardList(id) {
return this.state.myArray.map(item => {
if (item.id === id) {
return item.continent.map(c => { return <li> {c.name} </li>; });
}
else return null;
});
}