【问题标题】:Array with key of undefined coming through with React-Redux带有未定义键的数组通过 React-Redux
【发布时间】:2020-09-04 18:26:38
【问题描述】:

我设法使用 React-Redux 方法、useSelector 和 useDispatch 以及 React 的 useEffect 方法将数据从我的 json.server 获取到所需的组件中。

令我困惑的是,即使数组的内容在那里,它的键显示为未定义。

控制台输出: Screenshot of console log

组件:

import React, { useEffect } from 'react';
import SetlistItem from './SetlistItem';
import { fetchSongs } from '../../actions/index'

import { useSelector, useDispatch } from 'react-redux';

const SetlistContainer = () => {
  const songs = useSelector(state => state);

  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(fetchSongs())
  }, [dispatch])

  console.log(songs)

  return <div><SetlistItem /></div>
}

export default SetlistContainer;

动作:

export const fetchSongs = () => async dispatch => {
  const response = await songEntries.get("/songEntries");

  dispatch({ type: FETCH_SONGS, payload: response.data });
}

减速器:

export default (state = {}, action) => {
  switch (action.type) {
    case FETCH_SONGS:
      return { ...state, [action.payload.id]: action.payload };
    case CREATE_SONG:
      return { ...state, [action.payload.id]: action.payload };
    default:
      return state;
  }
}

db.json:

{
  "songEntries": [
    {
      "id": 1,
      "songTitle": "This is a song title",
      "notes": "These are some notes"
    }
  ]
}

【问题讨论】:

  • fetchSongs 长什么样子?
  • 减速器也会有帮助
  • 谢谢...我已将这些添加到操作中。
  • 结果songEntries.get("/songEntries")似乎没有id属性,而是包含具有这些属性的对象数组。

标签: json reactjs react-redux react-hooks


【解决方案1】:

我发现了问题。

我需要使用 lodash 库中的 mapKeys 方法。

我应该在操作中更清楚地说明我正在尝试获取一组记录,尽管毫无帮助,我只在占位符数组中放置了一个元素。

不管怎样,代码现在是这样的......

export default (state = {}, action) => {
  switch (action.type) {
    case FETCH_SONGS:
      return { ...state, ..._.mapKeys(action.payload, 'id') };
    case CREATE_SONG:
      return { ...state, [action.payload.id]: action.payload };
    default:
      return state;
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-24
    • 2023-01-14
    • 2019-01-15
    • 2023-04-10
    • 1970-01-01
    • 2021-08-05
    • 2018-06-01
    • 2020-06-21
    相关资源
    最近更新 更多