未捕获的类型错误:无法读取属性'地图'的未定义

Uncaught TypeError: Cannot read property 'map' of undefined with React

本文关键字:属性 未定义 地图 读取 类型 错误      更新时间:2024-02-18

我在React中实现了一个小的测试应用程序,通过AJAX获取数据,但它不能像集成的那样工作,因此我得到了以下错误:

Uncaught TypeError: Cannot read property 'map' of undefinedInline JSX script

代码如下:

<div id="content"></div>
<script type="text/jsx">   
var Bodypart = React.createClass({
    render: function() {
        return (
            <div>
                {this.props.name}
            </div>
        )
    }
})    
var BodypartList = React.createClass({
    getInitialState: function() {
      return {data: []};
    },
    componentWillMount: function() {
      $.ajax({
        url: this.props.url,
        dataType: 'json',
        success: function(data) {
          this.setState({bodyparts: data});
        }.bind(this),
        error: function(xhr, status, err) {
          console.error(this.props.url, status, err.toString());
        }.bind(this)
      });
    },
    render: function() {
        var bodypartItems = this.state.bodyparts.map(function (bodypart) {
            return (
                <Bodypart 
                    name={bodypart.name} 
                />
            );
        });
        return (
        <div>
            {bodypartItems}
        </div>
        );
    }
});    
React.render(
    <BodypartList url="/api/bodyparts/" />,
    document.getElementById('content')
);
</script>

来自/api/bodyparts/:的响应

{
    "bodyparts": [
        {
            "id": 1, 
            "name": "Face"
        }, 
        {
            "id": 3, 
            "name": "Mouth"
        }, 
        {
            "id": 2, 
            "name": "Nose"
        }
    ]
}

在初始渲染时,this.state.bodypartsundefined,因此出现错误。

你应该退回

{bodyparts:[]}

来自CCD_ 4。

此外,在success回调中,您应该设置如下状态:

this.setState(data);

因为您的api已经将bodyparts作为其结果的一部分返回。

this.state.bodyparts未定义。在ajax完成之前,该组件正在进行渲染。尝试设置初始状态