【发布时间】:2019-05-24 20:55:42
【问题描述】:
所以我有一个显示来自 firestore 的类别的组件,该组件第一次不显示任何内容,但是当我再次单击导航栏按钮时,它确实显示了存储在 firestore 中的数据。
这是组件文件:
import * as React from "react";
import Category from "./Category";
import connect from "react-redux/es/connect/connect";
import {getCategories} from "../reducers/actions/categoryAction";
class CategoriesList extends React.Component{
constructor(props) {
super(props);
this.state = ({
categoriesList: [{}]
})
}
componentWillMount() {
this.props.getCategories();
this.setState({categoriesList: this.props.categories});
this.forceUpdate();
}
render() {
return (
<div className={'container categories'}>
<div className={'row center'} onClick={() => this.props.history.push('/addcategories')}>
<div className={'col s24 m12'}>
<p>Create New Category</p>
</div>
</div>
<div className={'row'}>
<div className={'col s24 m12'}>
{/*{() => this.renderCategories()}*/}
{this.state.categoriesList && this.state.categoriesList.map(category => {
return <Category category={category} key={category.id}/>
})}
</div>
</div>
</div>
);
}
}
const mapDisptachToProps = (dispatch) => {
return {
getCategories: () => dispatch(getCategories()),
}
};
const mapStateToProps = (state) => {
return {
categories: state.category.categories
}
};
export default connect(mapStateToProps, mapDisptachToProps)(CategoriesList)
这里是reducer文件:
import db from '../firebaseConfig'
const initState = {
categories: []
};
const categoryReducer = (state=initState, action) => {
switch (action.type) {
case 'CREATE_CATEGORY':
db.collection("Categories").add({
category: action.category.name
})
.then(function(docRef) {
db.collection("Categories").get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
// console.log(`${doc.id} => ${doc.data().category}`);
if(doc.id === docRef.id) {
state.categories.push({id: doc.id, name: doc.data().category});
console.log(state.categories)
}
});
});
})
.catch(function(error) {
console.error("Error adding document: ", error);
});
break;
case 'GET_CATEGORIES':
console.log('Getting data from firestore');
db.collection("Categories").get().then((querySnapshot) => {
if(state.categories.length !== querySnapshot.size) {
querySnapshot.forEach((doc) => {
state.categories.push({id: doc.id, name: doc.data().category});
});
}
});
break;
}
return state;
};
export default categoryReducer
有没有办法在完全加载数据后更新组件?还是一种加载 initalState 中所有数据的方法?
【问题讨论】:
-
您是否尝试使用 ComponentDidMount 而不是 componentWillMount ?
-
@LeonardoLobato 是的,我试过
componentDidUpdate(prevProps) { if (prevProps.categoriesList.length !== this.categoriesList.length) { this.forceUpdate(); } } -
getCategories()是一个 AJAX 请求。当您在该请求之后setState时,尚未从 AJAX 响应中设置categories。 -
@Hoyen 我应该使用延迟吗?
-
componentDidMount 不是 componentDidUpdate... 可能你的意思是 componetWillReceiveProps 没有 componentDidUpdate。如果您使用正确的生命周期方法,您可能不需要它,您可以使用 this.forceUpdate()。尝试 componentDidMount,如果仍然不起作用,请尝试 componentWillReceiveProps
标签: node.js reactjs firebase redux google-cloud-firestore