Дублирование данных массива при отображении в React.js
изучаю React. Не могу понять, почему данные массива дублируются при отображении. Иными словами, почему на странице возникают копии пользователей (два пользователя с name Dmitry и name Sasha).
Reducer
const FOLLOW = "FOLLOW"
const UNFOLLOW = "UNFOLLOW"
const SET_USERS = "SET_USERS"
let initialState = {
users: []
};
const usersReducer = (state = initialState, action) => {
switch(action.type) {
case FOLLOW:
return {
...state,
users: state.users.map( u => {
if (u.id === action.userId) {
return {...u, followed: true}
}
return u;
})
}
case UNFOLLOW:
return {
...state,
users: state.users.map( u => {
if (u.id === action.userId) {
return {...u, followed: false}
}
return u;
})
}
case SET_USERS: {
return {
...state,
users: [...state.users, ...action.users ]}
}
default:
return state;
}
}
export const followAC = (userId) => ({type: FOLLOW, userId })
export const unfollowAC = (userId) => ({type: UNFOLLOW, userId })
export const setUsersAC = (users) => ({type: SET_USERS, users })
export default usersReducer;
Компонента-контейнер
import React from "react"
import { connect } from "react-redux"
import { followAC, setUsersAC, unfollowAC } from "../../redux/UsersReducer"
import Users from "./Users"
let mapStateToProps = (state) => {
return {
users: state.usersPage.users
}
}
let mapDispatchToProps = (dispatch) => {
return {
follow: (userId) => {
dispatch(followAC(userId));
},
unfollow: (userId) => {
dispatch(unfollowAC(userId));
},
setUsers: (users) => {
dispatch(setUsersAC(users));
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Users);
Компонента
import * as axios from "axios"
import React from "react"
import s from "./Users.module.css"
import usersPhoto from "./../../img/defaultUsersPhoto.jpg"
class Users extends React.Component {
constructor(props){
super(props)
this.props.setUsers(
[
{
id: 1,
photoUrl: null,
followed: false,
name: 'Dmitry',
},
{
id: 2,
photoUrl: null,
followed: true,
name: 'Sasha',
}]
)}
render() {
return (
<div className={s.wrapper}>
<div className={s.title}>Users</div>
<div>{this.props.users.map(u => <div key={u.id} className={s.user} >
<div className={s.ava}>
<div className={s.photoBlock}><img src={u.photoUrl != null ? u.photoUrl: usersPhoto} alt="logo" className={s.userAva}></img></div>
<div className={s.button}>
{u.followed
? <button className={s.button1} onClick={() => {this.props.unfollow(u.id)}}>Unfollow</button>
: <button className={s.button1} onClick={() => {this.props.follow(u.id)}}>Follow</button>
}
</div>
</div>
<div classNAme={s.body}>
<div className={s.userInfo}> <span className={s.fullName}>{u.name} </span>
<span className={s.status}>[ {u.status} ]</span></div>
</div>
</div>)}</div>
</div>
)
}
}
export default Users;