0

Рефакторю react-код под redux. Использовал useSelector в функции, где есть map. Почему выдаётся ошибка ? list является массивом объектов.

TypeError: Cannot read property 'map' of undefined

export const AnimalTable = () => {

const list = useSelector(state => state.list);

return (
        <table className="animals iteration5__table">
            <thead>
            <tr>
                ...
            </tr>
            </thead>
            <tbody>
            {list.map((item, index) => {
                return <AnimalRow key={index} content={item} index={index} />
            })}
            </tbody>
        </table>
)
}

2 ответа 2

0

list === 'undefined'. Необходимо проверить почему отсутствует значение в list. Если это только из-за того что данных временно нету нужно написать null-safe code:

<tbody>
   {list && list.map((item, index) => {
       return <AnimalRow key={index} content={item} index={index} />
     })}
</tbody>
0

Ошибка возникала из-за того, что я использовал combineReducers и указывал для каждого редюсера кастомное имя:

import {combineReducers} from "redux";
import reducerDemo11 from "./reducerDemo11";
import reducerAnimal from "./reducerAnimal";

export default combineReducers({
    demo11: reducerDemo11,
    animal: reducerAnimal,
})

Соответственно, в useSelector надо было указать правильный путь:

const list = useSelector(state => state.animal.list);

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.