【问题标题】:Cannot access only one object key in React Redux (all other keys are ok)无法在 React Redux 中仅访问一个对象键(所有其他键都可以)
【发布时间】:2020-08-12 12:19:36
【问题描述】:

在 React Redux 应用程序中,我有一个名为 ItemDetail 的组件,它当然应该呈现与它根据 URL 参数 id 检索的项目相关的所有细节。

import React, { useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux'
import * as actions from '../../../../../actions'

const ItemDetail = (props) => {
    const mapState = (state) => {
        return {
            currentItem: state.currentItem,
        }
    }

    const dispatch = useDispatch()
    const { currentItem } = useSelector(mapState)



    useEffect(() => {
        let { id } = props.match.params
        dispatch(actions.fetchCurrentItem(id))
        dispatch(actions.setAside(false))
        return () => dispatch(actions.setAside(true))
    }, [dispatch, props.match.params])



    return (

        <div id="item-detail">
            <div id="picture">picture {currentItem.image}</div>
            <div id="details">details {currentItem.name} {currentItem.rating[1]}</div>
        </div>
    );
}

export default ItemDetail;

Item 对象如下所示:

{
      "id": 1,
      "name": "Dell XPS 13",
      "value": "dell-xps-13",
      "category": 2,
      "department": 2,
      "price": 1599.0,
      "discount": 0,
      "image": "xps13_9370_4_3_01.jpg",
      "rating": {
        "1": 1,
        "2": 0,
        "3": 8,
        "4": 12,
        "5": 21
      },
      "sold": 520,
      "left": 34,
      "features": [
        "10th Generation Intel® Core™ i7-1065G7 Processor",
        "6.8% larger 16:10 display - 13 inches, 17% larger touchpad and an edge-to-edge backlit keyboard with larger key caps",
        "6% thinner design with more power",
        "long battery life —up to 18 hours, 49 minutes* on a Full HD+ model when using when using productivity applications like Word or Excel or up to 11 hours, 51 minutes* when streaming Netflix"
      ]
}

现在,我可以访问除“评分”之外的每个键。事实上,当我尝试访问 {currentItem.rating[1]} 时,我收到以下错误 TypeError: Cannot read property '1' of undefined。看起来对象是否未定义,但如果我只尝试访问 {currentItem.rating} 而不指定键值,我会按预期得到Error: Objects are not valid as a React child (found: object with keys {1, 2, 3, 4, 5}). If you meant to render a collection of children, use an array instead.

那么,当我尝试访问任何其他值时,或者只是 rating 找到了对象,但是当我尝试访问对象键(在本例中为“1”)时,对象是未定义的?

p>

感谢您的回复。

编辑

我感觉问题出在我的减速器上。以防万一,就在这里。

import * as actions from './../actions'

const initState = {
    loading: false,
    categories: [],
    currentCategory: {
        "id": 1,
        "value": "any",
        "name": "--- Any ---",
        "departments": []
    },
    currentDepartment: {
        "id": 0,
        "value": "any",
        "name": "--- Any ---",
    },
    toggler: 'hidden',
    error: '',
    minimumPrice: 0,
    maximumPrice: 5000,
    items: [],
    valueSearched: '',
    currentItem: {},
    aside: true
}

const rootReducer = (state = initState, action) => {
    switch (action.type) {
        case actions.SET_CATEGORY:
            return {
                ...state, currentCategory: action.payload.category, departments: action.payload.departments, currentDepartment: {
                    "id": 0,
                    "value": "any",
                    "name": "--- Any ---",
                }
            }
        case actions.FETCH_CATEGORIES_REQUEST:
            return { ...state, loading: true }
        case actions.FETCH_CATEGORIES_SUCCESS:
            return { ...state, loading: false, categories: action.payload }
        case actions.FETCH_CATEGORIES_FAILURE:
            return { ...state, loading: false, categories: action.payload }
        case actions.SET_DEPARTMENT:
            return { ...state, currentDepartment: action.payload }
        case actions.TOGGLE:
            return { ...state, toggler: action.payload }
        case actions.ASIDE:
            return { ...state, aside: action.payload }
        case actions.SET_MINIMUM_PRICE:
            return { ...state, minimumPrice: action.payload }
        case actions.SET_MAXIMUM_PRICE:
            return { ...state, maximumPrice: action.payload }
        case actions.FETCH_ITEMS_REQUEST:
            return { ...state, loading: true }
        case actions.FETCH_ITEMS_SUCCESS:
            return { ...state, loading: false, items: action.payload }
        case actions.FETCH_ITEMS_FAILURE:
            return { ...state, loading: false, items: action.payload }
        case actions.SET_VALUE_SEARCHED:
            return { ...state, valueSearched: action.payload }
        case actions.FETCH_CURRENT_ITEM_REQUEST:
            return { ...state, loading: true }
        case actions.FETCH_CURRENT_ITEM_SUCCESS:
            return { ...state, loading: false, currentItem: action.payload, aside: false }
        case actions.FETCH_CURRENT_ITEM_FAILURE:
            return { ...state, loading: false, currentItem: action.payload }
        default:
            return state
    }
}

export default rootReducer

【问题讨论】:

    标签: react-redux


    【解决方案1】:

    你可以这样访问它:

    {currentItem.rating["1"]}
    

    因为您的对象具有“字符串”排序

    更新: 检查此代码。它不完全是你的,但我认为它可以帮助你解决问题。

    <div id="details">raiting {Object.values(item.rating).join(",")} </div>
    

    https://codesandbox.io/s/fancy-field-j5j61?file=/src/MyComp.js

    【讨论】:

    • 这就像它还没有获取对象本身,但是使用其他键它可以工作。奇怪...
    • 也许您需要将{currentItem.rating} 放入循环中,并单独
  • mmm.. 我试过
      {currentItem.rating.map( itemRating=>
    • {itemRating}
    • )}
    但它说“无法读取属性”未定义的地图'
  • const detailsS​​tr = details ${currentItem.name} ${currentItem.rating['1']} 然后在 return 块中使用该字符串?
  • @c_thane,感谢您的提示。不幸的是,它返回'无法读取未定义的属性'1'......
  • 【解决方案2】:

    好的,经过研究,我找到了解决方案。

    基本上我的问题与this 重复。

    在我的情况下,我只需在减速器内将currentItem: null 设置为初始状态,然后在我的组件内return 检查currentItem 不是null,如果是这样,我就继续渲染整个组件。

    【讨论】:

      猜你喜欢
      相关资源
      最近更新 更多
      热门标签