我当时在做一个论坛项目,我用firestore作为后端数据库,进行响应和还原。 每当有人在没有评论的新帖子上发表评论时,我都会遇到问题,但它不会显示,但是出现刷新后,此后的所有评论都会正常显示。
github https://github.com/nikhilb2/Forum 部署http://mariosforum.surge.sh/signin
任何人都可以帮助我。
import React, { Component } from "react";
import { postComment } from "../../store/actions/projectActions";
import { connect } from "react-redux";
import moment from "moment";
class Comment extends Component {
constructor(props) {
super(props);
this.state = {
comment: "",
authorId: "",
projectId: ""
};
this.handleContent = this.handleContent.bind(this);
this.handlePost = this.handlePost.bind(this);
}
handleContent(e) {
this.setState({
comment: e.target.value,
projectId: this.props.projectId,
authorId: this.props.auth.uid
});
}
handlePost() {
this.props.postComment(this.state);
this.refs.comment.value = "";
}
render() {
const { user, project, state } = this.props;
console.log(`user`);
console.log(this.props);
return user ? (
<div className="container">
{project &&
project.comment &&
Array.isArray(project.comment) &&
project.comment.map(comment => {
const authorId = comment.authorId;
//console.log(user[authorId]);
//console.log(authorId)
return (
<div className="container project-details">
<div className="card z-depth-0">
<div className="card-content">
{comment.comment}
<div className="card-action grey lighten-4 grey-text">
{user[authorId] ? user[authorId].firstName : authorId}{" "}
{user[authorId] ? user[authorId].lastName : authorId}
<div>
{comment.time
? moment(comment.time.toDate()).calendar()
: authorId}
</div>
</div>
</div>
</div>
</div>
);
})}
<div className="card z-depth-0">
<div className="card-content">
<div className="input-field">
<label htmlFor="comment">Type Comment</label>
<textarea
id="comment"
ref="comment"
type="text"
className="materialize-textarea"
onChange={this.handleContent}
/>
</div>
<button
className="btn pink lighten-1 z-depth-0"
onClick={this.handlePost}
>
Post
</button>
</div>
</div>
</div>
) : null;
}
}
const mapDispatchToProps = dispatch => {
return {
postComment: project => dispatch(postComment(project))
};
};
const mapStateToProps = state => {
console.log(state);
return {
state: state
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(Comment);
答案 0 :(得分:1)
export const postComment = (project) => {
return(dispatch,getState,{getFirestore}) =>{
const firestore = getFirestore()
console.log(getState())
firestore.collection('projects').doc(project.projectId).update({
comment: firestore.FieldValue.arrayUnion({
comment:project.comment,
authorId:project.authorId,
time: new Date()})
}).then(()=>{
dispatch({
type:'POST_COMMENT',
project
})
}).catch((err)=>{
dispatch({type:'POST_COMMENT_ERROR'})
})
}}
您需要添加一个操作来更新redux存储库中的注释,因此每次发表评论时,它都会更新redux存储库中的
答案 1 :(得分:1)
这听起来与我在相同设置下遇到的问题相似。在index.js文件中的react-redux-firebase设置中添加以下行可能会解决此问题:
allowMultipleListeners: true