【发布时间】:2020-08-26 13:54:39
【问题描述】:
我正在创建一个网页,它有两个组件,一个 Categories 和两个 Items
借助函数 initCategories() 我在类别的 componentDidMount() 中调用,我能够在我的屏幕上显示所有类别。 initCategories() 函数调用负责从 Firestore 获取所有类别的操作
我想在启动时显示 Items 表中具有第一个类别 ID 的类别字段的所有项目在 Categories 表中。我使用 mapStateToProps 方法将 firstCategoryId 作为道具。我试图在 action.js 文件中调用一个操作,并在 items 内的 componentDidMount() 方法中传递此 ID,以便获取所有项目。
我该如何解决这个问题?
更新
Categories 表包含 categoryName 和 categoryId。 Items 表包含 itemId、itemName 和 category。 Item表中的category字段保存了item所属的category的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)
}
【问题讨论】:
-
ComponentDidMount gets called before the mapStateToProps() gets called。这不是真的,我不知道你为什么会有这种印象 -
是的,你是对的。我又检查了一遍。我将从帖子中删除该行
-
那我不明白这个问题。在
mapStateToProps中,您将firstCategoryId传递给组件。在componentDidMount中,您使用道具中的firstCategoryId调用initCategories() -
是的。并且我传递给 initCategories 方法的 firstCategoryId 原来是未定义的。这就是问题
-
我认为您没有以正确的方式访问状态属性。
state.reducer.currentCategoryId在启动时未定义,您需要在安装 react 本身之前在 store 中初始化该值
标签: javascript reactjs redux google-cloud-firestore react-redux