javascript - 尝试映射数组时出现错误。类型错误 : Cannot read property 'map' of undefined

标签 javascript json reactjs

因此,对于实践,我尝试使用 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/

相关文章:

javascript - Webpack - 在 Angular 2 中调用外部 JS

javascript - 如何覆盖 2.10.x 版中的 moment.js 区域设置格式,在 2.8.x 中有效

javascript - "Uncaught SyntaxError: Unexpected token"解析jsonp时

java - 使用 jackson 忽略 json 正文中的空元素

javascript - Material-UI useMediaQuery 最初没有识别正确的断点

validation - 使用 redux-form 我在输入第一个字符后失去焦点

javascript - 我如何在 React 中淡入变化的值?

javascript - 将字符串转换为分隔对象键

javascript - 来自外部文件的 jquery 未加载

Javascript,将两个数组组合成一种格式