我正在尝试使用 ReactJs 和 Firestore 创建类似于 reddit 的东西。当点击 upvote 按钮时,其 Firestore 文档中的帖子分数会更新,不知何故,当 React 重新获取文档时,id 丢失了。
这是日志的图片 - 请注意第二个日志中的第一项,分数增加了 1,但该项中的 id 丢失了:/而我没有投票的第二项,其 id 仍然完好无损。但是,如果我赞成第二项,它的 id 也会消失。
我的父组件:
import React, { Component } from 'react';
import { firestoreConnect, isLoaded } from 'react-redux-firebase';
import { connect } from 'react-redux';
import { compose } from 'redux';
import { upVote } from '../../Store/Actions/PostAction';
import PostCardV2 from '../PostCard/PostCardV2';
import AuthCard from '../Auth/AuthCard';
import SignedInCard from '../Auth/SignedInCard';
class Dashboard extends Component {
render() {
const { posts, auth } = this.props;
console.log(posts); // here is where i console logged
const list = posts && posts.map(post => {
return(
<PostCardV2 key={post.id} post={post} upVoted={()=>this.props.upVote(post.id, post.score)}/> //upvote is a dispatch function
);
})
if(!isLoaded(auth)) {
var rightBar = <p>Loading</p>
} else {
if (!auth.uid) {
rightBar = <AuthCard/>
} else {
rightBar = <SignedInCard userName={auth.email}/>
}
}
return(
<div className='container'>
<div className='row'>
<div className='col s8'>
{list}
</div>
<div className='col s4 sticky'>
{rightBar}
</div>
</div>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
auth: state.firebase.auth,
posts: state.firestore.ordered.posts
}
}
const mapDispatchToProps = (dispatch) => {
return {
upVote: (id, score) => dispatch(upVote(id, score))
}
}
export default compose(
connect(mapStateToProps, mapDispatchToProps),
firestoreConnect([
{ collection: 'posts', orderBy: ['score', 'desc']}
])
)(Dashboard);
我的孩子 PostCardV2 组件:
import React from 'react';
const PostCardV2 = (props) => {
const {imgUrl, title, content, score} = props.post;
return (
<div className='row'>
<div className='col s12'>
<div className='card'>
<div className='card-image'>
<img src={imgUrl}/>
</div>
<div className='card-content row'>
<div className='col s2'>
<div className='center' onClick={props.upVoted}>
<i className='small material-icons pointer-cursor'>arrow_drop_up</i>
<p>{score}</p>
</div>
</div>
<div className='col s10'>
<span className="card-title">{title}</span>
<p>{content}</p>
</div>
</div>
</div>
</div>
</div>
);
}
export default PostCardV2;
和我的调度功能:
export const upVote = (id, score) => {
return (dispatch, getState) => {
const newScore = score + 1;
firebase.firestore().collection('posts').doc(id).update({
score: newScore,
})
}
}