0

Я пытаюсь получить юзеров через 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)


1 ответ 1

1

Вам надо сделать Separation of Concerns в вашем коде. Полезно было бы перечитать туториал по Редаксу - https://redux.js.org/tutorials/essentials/part-1-overview-concepts.

То, как организован ваш store нарушает важное правило Редакса - редьюсеры не могут содержать side effects, в том числе асинхронных запросов. Редьюсер - это всегда банальная функция, которая не занимается сложной логикой.

Асинхронные запросы должны обрабатываться отдельными функциями. Как правило, в простых случаях используется middleware - thunks - https://github.com/reduxjs/redux-thunk.

Правильный флоу в таком случае выглядит так:

  1. Событие (клик по линку)
<span className="userPage__pagination-list_navig" onClick={this.getData}>prev</span>
  1. Вызов метода компонента getData(), возвращающую промис, обрабатывающий результат ajax-запроса, например, показывает попап с success/error.
    getData() {
          // requestUsers() - это thunk, который так же передается через connect
          return actions.requestUsers()
            .then(() => { console.log('success') }
            .catch((error) => {console.log(error)}))
        }
  1. Вызов thunk-функции, где в случае success происходит диспатч соответствующего action.
        function requestUsers() {
          //thunks have access dispatch
          return async dispatch => {
            try {
              const res = await axios.get(url)
              
              dispatch(setUserListSuccess(res.data))
              
              return res
            } catch {
              dispatch(setUserListError())
              through new Error('error')
            }
          }
        }
  1. Action creator передает соответствующий action и данные в редьюсер. А редьюсер возвращает новый объект с данными.
        // Action creator
        function setUsers(data) {
          return {
            type: 'CHANGE_PAGE',
            data
          }
        }
    
        // Reducer
        const userBaseReducer = (state = [], action) => {
          switch (action.type) {
            case "CHANGE_PAGE":
              return [
                ...state,
                action.data
              ]
          }
        }
  1. Реакт видит обновление пропсов и рендерит новый вью.
1

Ваш ответ

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

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