Я пытаюсь получить юзеров через axios запрос. Первый запрос происходит через componentDidMount для получения первой страницы. Он отрабатывает, я получаю первую партию юзеров. Далее когда с помощью пагинации хочу подгрузить еще юзеров, я вызываю отдельную функцию, которая меняет номер страницы в стейте и делает запрос. Данные приходят, но копирование их в стейт не происходит следовательно стейт не перерисовывается. Что я упустил?
import React from 'react'
import './usersPage.scss';
import UsersPageItem from './UsersPageItem';
import defaultAvatar from "./../../../../images/defaultUser.png"
import * as axios from "axios"
import './../../preloader.scss';
let classNames = require('classnames');
class UsersPage extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: false
}
this.totalCount = 0
this.pagesArray = []
}
componentDidMount() {
if (!this.pagesArray.length) {
this.setState({ isLoading: true })
axios.get(
`https://social-network.samuraijs.com/api/1.0/users?page=${this.props.currentUsersPage}&count=${this.props.displayedUsers} `
)
.then(response => {
this.totalCount = response.data.totalCount
if (this.pagesArray.length < response.data.items.length) {
this.props.setUsers(response.data.items, response.data.totalCount)
}
this.setState({ isLoading: false })
})
}
}
render() {
let pagesCount = Math.ceil(this.totalCount / this.props.displayedUsers)
for (let i = 1; i <= pagesCount; i++) {
this.pagesArray.push(i)
}
return (
<div className="userPage__wrapper">
{
this.state.isLoading
? <section><span className="load"></span></section>
: <>
{
this.props.userBase
//.slice(0, showItem) =>to show only some elements
? this.props.userBase.slice(0, this.props.displayedUsers).map((user, index) => (user ? <UsersPageItem
key={this.props.userBase[index].userId}
//data
userBase={this.props.userBase}
currentUserId={this.props.currentUserId}
userAvatar={this.props.userBase[index].avatarUrl
? this.props.userBase[index].avatarUrl
: defaultAvatar}
userName={this.props.userBase[index].name}
registerDate={this.props.userBase[index].registerDate}
userId={this.props.userBase[index].userId}
statusText={this.props.userBase[index].statusText}
//functions
toFollow={this.props.toFollow}
toChat={this.props.toChat}
/> : null))
: null
}
<ul className="userPage__pagination-list">
<span className="userPage__pagination-list_navig" onClick={(event) => {
//функция которая не срабатывает//////
this.props.ChangePage(event)
//////////////////////////////////////
}} >prev</span>
<div className="userPage__pagination-list_pages-container" >
{/* creating pagination and comparing it with state current selected page */}
{this.pagesArray.slice(0, 10).map(item => <li className={classNames("userPage__pagination-list_item", { " active": item === this.props.currentUsersPage })}
key={item} name={item} onClick={(event) => {
this.props.ChangePage(event)
this.setState({ isLoading: false })
}}>{item}</li>)}
</div>
<span className="userPage__pagination-list_navig" onClick={(event) => {
this.props.ChangePage(event)
}} >next</span>
<span className="userPage__pagination-list_total" >total: {this.totalCount}</span>
</ul>
</>
}
</div>
)
}
}
export default UsersPage;
//==============================================================
// код из редьюсера
export let initialUsersState = {
userBase: [],
currentUserId: localStorage.getItem("currentUserId"),//<<<== USER
displayedUsers: 4,
totalUsersCount: 0,
currentUsersPage: 1
}
const userBaseReducer = (state = initialUsersState, action) => {
let newState = {
userBase: [...state.userBase],
...state
}
switch (action.type) {
case "SET_USERS":
return {
...newState,
userBase: [...action.newUsers, ...newState.userBase],
totalUsersCount: action.totalCount
}
case "CHANGE_PAGE":
const loadData = async (event) => {
let lastPage = Math.ceil(newState.totalUsersCount / newState.displayedUsers)
if (event.target.textContent === "prev" && newState.currentUsersPage > 1) {
--newState.currentUsersPage
} else if (event.target.textContent === "next" && newState.currentUsersPage < lastPage) {
++newState.currentUsersPage
} else if (event.target.attributes.name !== undefined) {
newState.currentUsersPage = +event.target.attributes.name.value
}
await axios.get(`https://social-network.samuraijs.com/api/1.0/users?page=${newState.currentUsersPage}&count=${newState.displayedUsers}`)
.then(response => {
//данные из responce получаю
// но в стейт копирование не идет
return {
userBase: [...response.data.items, ...newState.userBase],
...newState,
}
})
}
loadData(action.event)
break
default: return newState
}
return newState
}
export const SET_USERS_actionCreator = (newUsers, totalCount) => {
return {
type: "SET_USERS",
newUsers: newUsers,
totalCount: totalCount
}
}
export const CHANGE_PAGE_actionCreator = (event) => {
return {
type: "CHANGE_PAGE",
event: event
}
}
//==============================================================
// код из коннектора
import PublicUserPage from './../UserPage/PublicUserPage';
import { connect } from 'react-redux'
import {
SET_USERS_actionCreator,
CHANGE_PAGE_actionCreator
} from './../../../../redux/userBaseReducer';
let mapStateToProps = (state) => {
return {
userBase: state.usersReducer.userBase,
currentUserId: state.usersReducer.currentUserId,
displayedUsers: state.usersReducer.displayedUsers,
totalUsersCount: state.usersReducer.totalUsersCount,
currentUsersPage: state.usersReducer.currentUsersPage
}
}
let mapDispatchToProps = (dispatch) => {//functions for connect is dispatch
return {
setUsers: (newUsers, totalCount) => {
dispatch(SET_USERS_actionCreator(newUsers, totalCount))
},
ChangePage: (event) => {
dispatch(CHANGE_PAGE_actionCreator(event))
}
}
}
const PublicUserPageContainer = connect(mapStateToProps, mapDispatchToProps)(PublicUserPage)