【问题标题】:React/redux : this.props returns undefined value + arrayReact/redux:this.props 返回未定义的值 + 数组
【发布时间】:2018-04-14 18:17:16
【问题描述】:

我正在使用 React/redux 构建我的应用程序。

这是我的数据(json)

{
  "categories": [
    {
      "id": 1,
      "name": "category 1",
      "slug": "category-1"
      "content": [
        {
          "id": 1,
          "title": "title 1 "
        },
        {
          "id": 2,
          "title": "title 2 "
        }
      ]
    }
  ]
}

我想做什么:

  1. 选择一个类别
  2. 显示所选类别的内容

我的店就是这样的:

categoryItems: [], // list of categories
categorySelected: []

当我选择一个类别时,数据会正确保存在我的状态

在 Category 组件上,我实现了 selectCategory 函数,它调用操作 SELECT_CATEGORY 并将数据分派到 reducer。到目前为止一切顺利!

getCategoryList() {
   return this.props.categories.map((category) => {
     return (<li key={category.id}> 
            <Link to={`/category/${category.slug}`} onClick={() =>this.props.selectCategory(category.slug)} >{category.name} </Link>)});}

在 CategoryDe​​tail 上,当我 console.log(this.props.categorySelected.name) 我得到:

undefined
name

这是问题,因为我无法读取 this.props.categorySelected.name 如何解决这个问题并正确阅读这个道具?

【问题讨论】:

  • 你确定只有{category.name} 是未定义的吗?您可以尝试验证该对象的其他属性以查看打印内容吗?
  • 该对象的所有属性都未定义。示例:如果我控制台日志 category.id,它显示未定义和 id

标签: redux react-redux react-props


【解决方案1】:

您必须将完整的对象提供给您的 selectCategory() 函数。

像这样:

getCategoryList() {
   return this.props.categories.map((category) => {
     return (<li key={category.id}> 
            <Link to={`/category/${category.slug}`} onClick={() =>this.props.selectCategory(category)} >{category.name} </Link>)});
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-08
    相关资源
    最近更新 更多