因此,对于实践,我尝试使用 react 框架消耗休息点。 但不知怎的,我得到了这样的错误:
TypeError: Cannot read property 'map' of undefined
Json 看起来像这样:
{
"name":"sadasd.tx",
"application":"Word",
"id":"123",
"type":"Mixed",
"containers":[
"Variant1",
"Variant2_sch",
"Variant5",
"Variant6",
"Variant3",
"Variant4"
]
}
React 组件如下所示:
class ContainerList extends React.Component{
constructor(props){
super(props);
this.state={fileContent: []};
}
componentDidMount(){
fetch('http://localhost:8080/'+ this.props.file)
.then(res => res.json())
.then((data) => {
this.setState({fileContent: data})
})
}
render() {
const containerNames = this.state.fileContent.containers.map(container => <Container containerName={container} />);
return (
<table>
<tbody>
{containerNames}
</tbody>
</table>
)
}
}
删除数组上的映射并在浏览器中调试后,我看到 json 对象已正确分配给变量。但是当迭代它时,我得到了未定义的错误。有人知道可能出了什么问题吗?
[编辑] 我对此完全不明白。在你们发帖之后,我确实明白为什么它会抛出这个错误。但在阅读你的答案后我做了这样的事情:
我向 state
添加了另一个具有默认 true 值的变量 isLoading
。在获取 json 后的 fetch 中,我将其设置为 false。
fetch('http://localhost:8080/'+ this.props.xx)
.then(res => res.json())
.then((data) => {
this.setState({fileContent: data, isLoading: false})
})
在渲染方法中我添加了 if 语句:
render() {
let containerNames;
if(this.state.isLoading){
containerNames = <h1>Loading</h1>
}else{
containerNames = this.state.fileContent.listContainers.map(listContainer => <Container listContainerName={listContainer} />);
}
return (
<table>
<tbody>
{containerNames}
</tbody>
</table>
)
所以在获取数据之前不应该输入else语句。但 React 正在以某种方式做到这一点。并抛出错误。
最佳答案
在初始渲染期间,this.state.fileContent.containers
的值将是未定义的,并且 undefined
没有 map
方法
您在map
之前添加检查
const containerNames = Array.isArray(this.state.fileContent.containers) && this.state.fileContent.containers.map(
关于javascript - 尝试映射数组时出现错误。类型错误 : Cannot read property 'map' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56584919/