为了账号安全,请及时绑定邮箱和手机立即绑定

尝试映射数组时出错。类型错误:无法读取未定义的属性“地图”

尝试映射数组时出错。类型错误:无法读取未定义的属性“地图”

鸿蒙传说 2021-06-30 07:19:54
所以对于练习,我试图用反应框架消耗休息点。但不知何故,我收到如下错误:TypeError: Cannot read property 'map' of undefinedJson 看起来像这样:{     "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另一个isLoading具有默认真值的变量。在获取 json 后,我将其设置为 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>        )所以在fetchind数据之前应该不可能进入else语句。但反应以某种方式这样做。并抛出错误。
查看完整描述

2 回答

?
慕斯王

TA贡献1864条经验 获得超2个赞

在初始渲染期间的值this.state.fileContent.containers将是未定义的,并且undefined没有map方法

您之前添加检查 map

const containerNames = Array.isArray(this.state.fileContent.containers) && this.state.fileContent.containers.map(



查看完整回答
反对 回复 2021-07-01
?
HUX布斯

TA贡献1876条经验 获得超6个赞

const { fileContent } = this.state

const { containers } = fileContent

const containerName = containers ? containers : []

就像提到的其他答案一样,在初始渲染期间容器不存在。在这里,我根据个人喜好做了一些解构,但我只是说明容器是否存在,然后映射它,否则映射一个空数组


查看完整回答
反对 回复 2021-07-01
  • 2 回答
  • 0 关注
  • 241 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号