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

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

我已经在 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.bodyparts 未定义。该组件在 ajax 完成之前呈现。尝试设置初始状态

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

你应该return

{bodyparts:[]}

来自 getInitialState.

另外,在您的 success 回调中,您应该将状态设置为:

this.setState(data);

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