带有未定义键的数组通过 React-Redux



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

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

控制台输出: 控制台日志的屏幕截图

该组件:

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"
}
]
}

我发现了问题。

我需要使用 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;
}
}

最新更新