【问题标题】:TypeError: Cannot read property 'post' of null"类型错误:无法读取 null 的属性“帖子”
【发布时间】:2016-07-23 06:10:14
【问题描述】:

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

我得到:

内联 JSX 脚本:29Uncaught TypeError: Cannot read property 'post' of null

而且我不知道为什么会出现错误。

我已经测试过,如果我将:{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>

【问题讨论】:

    标签: javascript jquery ajax api reactjs


    【解决方案1】:

    组件的初始状态永远不会设置,默认为null。在你的组件中添加一个函数getInitialState

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-03
      • 2023-01-31
      • 2019-11-02
      • 2017-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多