javascript - react 教程 : Uncaught TypeError: Cannot read property 'data' of null

标签 javascript reactjs

我正在关注 React 教程:http://facebook.github.io/react/docs/tutorial.html

我只是之后 http://facebook.github.io/react/docs/tutorial.html#fetching-from-the-server

我在 SO 上经历了类似的问题,但没有找到适合我的具体案例的解决方案。

var data = [
    {author: "Pete Hunt", text: "This is one comment"},
    {author: "Jordan Walke", text: "This is *another* comment"},
    {author: "Bob Lilly", text: "This is *another* comment 2"}

];

var Comment = React.createClass({
    render: function() {
        var rawMarkup = marked(this.props.children.toString(), {sanitize: true});
        return (
            <div className="comment">
                <h2 className="commentAuthor">
                    {this.props.author}
                </h2>
                <span dangerouslySetInnerHTML={{__html: rawMarkup}} />
            </div>
        );
    }
});

var CommentList = React.createClass({
    render: function() {
        var commentNodes = this.props.data.map(function (comment) {
            return (
                <Comment author={comment.author}>
                    {comment.text}
                </Comment>
            );
        });
        return (
            <div className="commentList">
                {commentNodes}
            </div>
        );
    }
});

var CommentForm = React.createClass({
    render: function() {
        return (
            <div className="commentForm">
                <br/>Hello, world! I am a CommentForm.
            </div>
        );
    }
});

var CommentBox = React.createClass({
    render: function() {
        return (
            <div className="commentBox">
                <h1>Comments</h1>
                <CommentList data={this.props.data} /> 
                <CommentForm />
            </div>
        );
    }
});


React.render(
    // <CommentBox url="comments.json" />, 
    <CommentBox data={data} />,
    document.getElementById('content')
);

当我尝试使用从服务器获取的数据时(第一步 --> 参见第二个链接),我收到此错误:

Uncaught TypeError: Cannot read property 'data' of null

我猜这与以错误的方式传递数据有关。

编辑:我用目前给出的答案编辑了鳕鱼

编辑 2:现在它可以处理哑数据(var data = [ ...),但不能处理从服务器获取的数据

最佳答案

您正在将 data 作为 prop 发送到 CommentBox 并尝试通过 CommentBox 状态传递它。

<CommentList data={this.props.data} />

代替

<CommentList data={this.state.data} />

我通常这样推理 Prop ; Props 是即将到来的东西,State 是已经存在的东西。

关于javascript - react 教程 : Uncaught TypeError: Cannot read property 'data' of null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32489741/

相关文章:

javascript - 如何在 JEST 中测试下载文件的请求

javascript - React,在主函数外部声明的 if else 比较函数中出错

javascript - 使用 .NET Core 2.0 Web api 上传 HTML5 文件

javascript - YouTube iframe加载的脚本不会超过Google的页面速度

javascript - AngularJS 中的注销页面

javascript - 让 for...of 跳过循环最后一个元素

javascript - 在悬停时为列表中的 sibiling li 元素设置样式

php - 在 "Laravel + React"项目上使用 JEST 来测试应用程序 API(后端)

javascript - CSS3 Flip Dropdown Menu - 悬停在子菜单上时保留主菜单悬停样式

reactjs - 在Next.js网站中打开页面作为覆盖