【问题标题】:Automatically Populate list on webpage startup - React, Redux, Firebase网页启动时自动填充列表 - React、Redux、Firebase
【发布时间】: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

ma​​pStateToProps()

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


【解决方案1】:

我终于解决了这个问题。谢谢大家,尤其是@gbalduzzi 帮我解决了这个问题。

据我了解的实际问题: 创建商店时,reducer 会使用默认值初始化。那是第一次调用 componentDidMount() 的时候。当下载来自 firebase 的值时,组件会更新。这一次,被触发的是 componentDidUpdate() 方法。

componentDidUpdate()

解决方案:
我添加了以下代码。有了这个,我只在组件使用来自 firebase 的值更新时才加载项目。

componentDidUpdate(prevProps, prevState, snapshot) {
  if(this.props.currentCategoryId!== prevProps.currentCategoryId){
    this.props.loadItemsInCategory(this.props.currentCategoryId)
  }
}

【讨论】:

  • @gbalduzzi 希望我的回答没有出错
【解决方案2】:

你为什么不使用钩子?

对于使用钩子的无状态组件,您可以执行以下操作:

// items.jsx
const { categoryId } = props;
const [items, setItems] useState([]);

useEffect(() => {
  fetchItemsByCategoryId(categoryId).then(items => setItems(items));
}, [categoryId])

return <ul>{items.map((item) = <li><Item item={item} /></li>)</ul>

我建议您阅读以下文档: https://reactjs.org/docs/hooks-intro.html

【讨论】:

  • 我没有使用钩子。我使用类
  • 在 OP 案例中使用 componentDidMount 有什么区别?风格偏好之外
猜你喜欢
  • 1970-01-01
  • 2018-01-18
  • 1970-01-01
  • 2011-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-04
  • 2015-02-23
相关资源
最近更新 更多