Hello. Help new in redux .
Why in this approach, the application breaks by displaying an error:
Cannot read property 'map' of undefined
renderListHandler(){ return this.props.heroes.map(hero => { return ( <div key={hero.name}> <h4 onClick={this.props.onClickOneOfVariant}>{hero.name}</h4> </div> ) }) } renderImagesHandler(){ const heroes = this.props.heroes;//Добавляем переменную героев чтобы внизу использовать дважды const image = ~~(Math.random() * heroes.length); //Берем случайную картинку из героев return heroes[image].src; //Возвращаем картинку } render(){ const arr = this.renderListHandler(); //Возвращаем весь массив суда const shuffledArr = shuffle(arr); //Shuffle простой алгоритм чтобы перемещать массив ничего серьезного return ( <Container className="h-100"> <img src={this.renderImagesHandler()} alt="secret" /> //Показываем тут одну случайную картинку {shuffledArr} //Показываем тут перемещанный массив героев </Container> ) } This is part of Redux
const mapStateToProps = state => { return { heroes: state.nameAndImage, ctr:state.counter }; } const mapDispatchToProps = dispatch => { return { onClickOneOfVariant:() => dispatch({type:"TRUEVARIANT"}) }; }; This is a reducer
const initialState = { counter:0, nameAndImage:data } const rootReducer = (state = initialState, action) => { if(action.type === "TRUEVARIANT"){ return { counter:state.counter + 1, } } return state; } And data comes to him like this
export const data = [{ src: Vers, name: "Captain Marvel" }, { src: Venom, name: "Venom" }, { src: Thanos, name: "Thanos" }] src inside data are pictures that I connected indicating the name to everyone
example: import Vers from "../assets/marvel/vers.jpg";
And used this Vers inside data
Without this onClickOneOfVariant event, everything works perfectly.
But if you add it, the page loads, but when you click on one of h4 displays an error
Cannot read property 'map' of undefined.
What am I doing wrong please tell me?
heroes- liesundefined, hence the error. Write throughdefaultPropsdefault value, an empty array will be normal. In the case of Ridax, initialize the variable in the props with an empty array initially. - Denis BubnovinitialStatein the reducer. Most examples will have this initial state. AboutdefaultPropsyou can look here: Typechecking With PropTypes - Denis Bubnov 7:34 pm