我正在创建一个包含两个组件的网页,一个是类别,两个是项目
借助initCategories()函数,我可以在Categories的componentDidMount()内部调用,从而可以在屏幕上显示所有类别。该initCategories()函数调用,负责获取来自公司的FireStore所有类别的行动
我想在启动时显示“项目”表中具有“类别”字段和“类别”表中第一类别ID的所有项目。我使用mapStateToProps方法将firstCategoryId用作道具。我试图在action.js文件中调用一个动作,并在项目内部的componentDidMount()方法中传递此ID,以获取所有项目。
我该如何解决?
更新资料
类别表包含categoryName和categoryId。Items表包含itemId,itemName和类别。项目表中的类别字段保存该项目所属类别的ID
mapStateToProps()
const mapStateToProps = state => {
console.log("mapping called")
return {
items: state.itemReducer.itemsOnDisplay,
currentCategoryId: state.reducer.currentCategoryId
};
}
const mapDispatchToProps = dispatch => {
return{
// onCategoryAdded: (category) => dispatch(actionCreators.addCategory(category)),
// onCategoryDeleted: (categoryId) => dispatch(actionCreators.deleteCategory(categoryId)),
loadItemsInCategory: (categoryId) => dispatch(itemActionCreators.loadItemsInCategory(categoryId)),
}
}
componentDidMount()
componentDidMount(){
this.props.loadItemsInCategory(this.props.currentCategoryId)
}
我终于解决了问题。谢谢大家,尤其是@gbalduzzi帮助我解决了这个问题。
据我了解,实际的问题是:创建存储后,reducer将使用默认值初始化。那是第一次调用componentDidMount()的时候。从Firebase下载值后,组件将更新。这次是被触发的componentDidUpdate()方法。
componentDidUpdate()
解决方案:
我添加了以下代码。这样,仅当组件使用Firebase中的值更新时,我才加载项目。
componentDidUpdate(prevProps, prevState, snapshot) {
if(this.props.currentCategoryId!== prevProps.currentCategoryId){
this.props.loadItemsInCategory(this.props.currentCategoryId)
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句