Javascript 未捕获的类型错误:无法使用 React 读取未定义的属性“地图”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28630005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:08:46  来源:igfitidea点击:

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

javascriptreactjs

提问by JavaCake

I have implemented a little test application in React to fetch data via AJAX, but it is not working as inteded, hence i get following error:

我在 React 中实现了一个小测试应用程序以通过 AJAX 获取数据,但它没有按预期工作,因此我收到以下错误:

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

Code is as following:

代码如下:

<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>

The response from /api/bodyparts/:

来自 的回应/api/bodyparts/

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

回答by nilgun

At initial render this.state.bodypartsis undefinedhence the error you got.

在最初的渲染this.state.bodypartsundefined因此你得到了错误。

you should return

你应该回来

{bodyparts:[]}

from getInitialState.

getInitialState.

Also in your successcallback you should set state like:

同样在您的success回调中,您应该设置如下状态:

this.setState(data);

because your api already returns bodypartsas part of its result.

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

回答by Joe Fitter

this.state.bodypartsis undefined. the component is rendering before the ajax has completed. Try setting an initial state

this.state.bodyparts未定义。组件在 ajax 完成之前呈现。尝试设置初始状态