我正在使用react / redux / mongo / express / nodejs(stack)以防信息有所帮助。问题是,当我点击刷新我的帖子似乎消失了。用户可以点击帖子列表中的帖子,它会显示帖子就好了,但是当我点击刷新时,帖子就不再显示了。我将发布以下代码来帮助。
编辑:这是服务器端代码,用于显示我在后端拨打电话的内容。
这位于router.js页面上:
app.get('/posts/:id', Posts.getOnePost);
这位于帖子控制器页面上:
exports.getOnePost = function(req, res, next) {
Posts.findById(req.params.id).populate("comments").exec(function(err, foundPost) {
if(err) {
return next(err);
} else {
res.json(foundPost);
}
});
}
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import * as actions from '../../actions/posts_actions';
import _ from 'lodash';
class ShowPosts extends Component {
constructor(props) {
super(props);
this.onDeleteClick = this.onDeleteClick.bind(this);
this.deleteComment = this.deleteComment.bind(this);
}
componentDidMount() {
const {id} = this.props.match.params;
this.props.getOnePost(id);
}
renderComments() {
const { post } = this.props;
return post.comments.map((comment) => {
return (
<li className="list-group-item" key={comment._id}>
{comment.text}
<button
onClick={this.deleteComment, comment.id}
className="btn btn-xs btn-danger">
Delete
</button>
<Link
to={`/posts/${post.id}/comments/${comment.id}/edit`}
className="btn btn-xs btn-warning">
Edit
</Link>
</li>
);
});
}
deleteComment(comment_id) {
const {id} = this.props.match.params;
this.props.deleteComments(id, comment_id, () => {
this.props.history.push(`/posts/${id}`);
});
}
onDeleteClick() {
const {id} = this.props.match.params;
this.props.deletePost(id, () => {
this.props.history.push("/");
});
}
render() {
const { post } = this.props;
if (!post) {
return <div> Loading...No Post </div>;
}
return (
<div>
<Link className="btn btn-primary" to="/posts">Back To Post</Link>
<button
className="btn btn-danger pull-xs-right"
onClick={this.onDeleteClick}
>
Delete Post
</button>
<Link
className="btn btn-success pull-right"
to={`/posts/${post.id}/edit`}>
Edit Post
</Link>
<h3>{post.title}</h3>
<p>{post.content}</p>
<ul className="list-group">
{this.renderComments()}
</ul>
<Link
className="btn btn-warning btn-xs"
to={`/posts/${post.id}/comments/new`}>
Comment
</Link>
</div>
);
}
}
function mapStateToProps({ posts }, ownProps) {
return { post: posts[ownProps.match.params.id] };
}
export default connect(mapStateToProps, actions)(ShowPosts);
以下是getOnePost操作:
export function getOnePost(id) {
return function(dispatch) {
axios.get(`${ROOT_URL}/posts/${id}`)
.then((response) => {
dispatch({
type: GET_POST,
payload: response
});
})
.catch((error) => {
console.log(error);
});
}
}
答案 0 :(得分:0)
目前尚不清楚帖子的身份来自哪里。如果它是反应应用程序状态的一部分,那么当你点击刷新时它会被消灭。刷新后,您的javascript将从服务器下载并从干净状态重新开始。
如果id是路由的一部分,那么你的组件将有机会恢复它。
在mapStateToProps中,您声明该帖子是您通过索引从州的帖子部分提取的内容。刷新此帖子后,部分状态可能为空。