TypeError:无法读取属性'帖子'“为空”;

TypeError: Cannot read property 'post' of null"

本文关键字:帖子 为空 读取 属性 TypeError      更新时间:2023-12-07

我刚开始使用React,当我尝试执行Ajax调用时,遇到了一些麻烦。

我得到:

内联JSX脚本:29Uncaught TypeError:无法读取null 的属性"post"

我不知道为什么我会出错。

我已经测试过了,如果从render函数中去掉:{this.state.post},则alert(data)的响应是正确的。

有人能帮我吗?

   <script type="text/jsx">
        var SomeComponent = React.createClass({
            render: function(){
                return(
                            <h3>{this.props.header}</h3>
                    );
            }
        });
        React.render( <SomeComponent header="Dette er en tittel :)"/>, document.getElementById('content'));
        var EinarsComponent = React.createClass({
            componentDidMount: function(){
            $.ajax({
                url: "https://api.bring.com/shippingguide/api/postalCode.html",
                data: {clientUrl: "localhost", pnr: "4879"},
                success: function(data){
                    this.setState({post: data});
                    alert(data);
                }.bind(this)    
            });
        },
            render: function(){
                return(         
                        <div>{this.state.post}</div>
                    );
            }
        });
        React.render(<EinarsComponent />, document.getElementById('hei'));
    </script>

组件的初始状态从未设置,默认为null。在组件中添加函数getInitialState

getInitialState: function(){
  return {
    post: null // Or some other default value that you fancy
  };
}