gpt4 book ai didi

javascript - Rails 和 React : TypeError: Cannot call method 'map' of undefined

转载 作者:太空宇宙 更新时间:2023-11-03 16:45:49 24 4
gpt4 key购买 nike

我在我的 Rails 项目上使用 React 制作 Post 系统。但是,当我尝试在我的主页中呈现帖子时,出现此错误:

React::ServerRendering::PrerenderError in HomeController#index Encountered error "TypeError: Cannot call method 'map' of undefined" when prerendering PostsList with {"posts":null} React.createClass.render ((execjs):19669:38)

我的代码是上面的:

posts_list.js.jsx:
var PostsList = React.createClass({
getInitialState: function() {
return { posts: this.props.initialPosts };
},

render: function() {
var posts = this.state.posts.map(function(post) {
return <Post key={post.id} post={post} />;
});

return (
<div className="posts">
{posts}
</div>
);
}
});

post.js.jsx

var Post = React.createClass({
render: function() {
return (
<div className="post">
<PostTitle post={this.props.post} />
<PostBody post={this.props.post} />
</div>
);
}
});

var PostTitle = React.createClass({
render: function() {
return (
<div className="post-header">
<h2>{this.props.post.title}</h2>
<div className="post-meta">
By {this.props.post.user_id} - {this.props.post.created_at}
</div>
</div>
);
}
});

var PostBody = React.createClass({
render: function() {
return (
<div className="post-contents">
{this.props.post.body}
</div>
);
}
});

和index.html.erb

<div class="container-fluid">
<div class="col-md-8">
<h3> Posts Feed </h3>
<%= react_component('PostsList', {initialPosts: @posts }, {prerender: true}) %>
</div>
</div>

post_controller.rb

def index
@posts = Post.all
@user = current_user
end

当我使用 {initialPosts: Post.All } 它有效,但是当我使用 @posts 时,它无效

知道为什么会这样吗?我已经在网站上发帖并且@posts 不为空。

最佳答案

好的,我发现出了什么问题,我在主页布局中渲染 react ,但@posts 是在帖子 Controller 而不是主页 Controller 中定义的。

关于javascript - Rails 和 React : TypeError: Cannot call method 'map' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33230308/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com