@rew232edewqe

Как исправить бесконечное обновление Redux?

Суть вопроса в том что, когда использую в componentDidMount в App все нормально подгружает данные один раз, но почему то при вводе в поле поиска таргет с поля сбивается.
А также (ниже код представлен), когда использую в componentDidMount в ListEmployee с этим же запросом, он бесконечно посылает запросы. Я так понимаю класс ListEmployee обновляется бесконечно при помощи Route?
Буду благодарен за помощь =). С этим редаксом как то все запутанно.
Может кто еще подскажет в какую сторону двигаться.

import React from 'react';
import ReactDOM from 'react-dom';
import App from './js/App';
import './css/style.css';
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/js/bootstrap'
import './css/style2.sass';
import * as serviceWorker from './serviceWorker';
import {Provider} from "react-redux";
import {applyMiddleware, createStore} from "redux";
import indexReducer from "./js/reducers/indexReducer";
import {composeWithDevTools} from "redux-devtools-extension";
import thunk from "redux-thunk";


const store = createStore(indexReducer,composeWithDevTools(applyMiddleware(thunk)))

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById('root'));

serviceWorker.unregister();

store.subscribe(() => console.log(store.getState()));


import React,{Component} from 'react';
import Pagination from "../Pagination/Pagination";
import _ from "lodash";
import {PAGE_SIZE, SERVER_API_CONNECT} from "../../core/Constant";
import {connect} from "react-redux";
import Loader from "../Loader/Loader";
import {mapStateToProps} from "../../store/stateToProps";
import {mapDispatchToProps} from "../../store/dispatchToProps";
import Filter from "../Filter/Filter";
import { withRouter } from 'react-router-dom'




class ListEmployee extends Component{

    async сomponentDidMount() {
        this.props.getFetchData(`${SERVER_API_CONNECT}/employee/search?search=`,this.props.listEmployees.search)
    }

    render() {
        const {listEmployees,setSearchEmployees} = this.props
        const displayDataPage = _.chunk(listEmployees.employees, PAGE_SIZE)[this.props.currentPage]
        const pageCount = Math.ceil(listEmployees.employees.length / PAGE_SIZE)

        console.log(this.props.listEmployees.employees.map(item => item.name))

        function onSort(Field) {
            return Field;
        }

        return (
            <div className="content">
                <Filter search={listEmployees.search} setSearchEmployees={setSearchEmployees.bind(this)}/>
                <table className="table">
                    <thead className="thead-light">
                    <tr>
                        <th onClick={() => onSort("id")}>Id <small>{this.props.sortField === "id" ? this.props.sort : null}</small>
                        </th>
                        <th onClick={() => onSort("name")}>Имя сотрудника
                            <small>{this.props.sortField === "name" ? this.props.sort : null}</small>
                        </th>
                        <th onClick={() => onSort("organizationId.name")}>Организация
                            <small>{this.props.sortField === "organizationId.name" ? this.props.sort : null}</small>
                        </th>
                        <th onClick={() => onSort("employerId")}>Руководитель
                            <small>{this.props.sortField === "employerId" ? this.props.sort : null}</small>
                        </th>
                    </tr>
                    </thead>
                    <tbody>
                    {(this.props.isLoading || _.isEmpty(listEmployees.employees)) ? <tr>
                            <td><Loader/></td>
                        </tr> :
                        listEmployees.employees.map((item) => (
                            <tr key={item.id}>
                                <td>{item.id}</td>
                                <td>{item.name}</td>
                                <td>{_.isNull(item.organizationId) ? '' : item.organizationId.name}</td>
                                <td>{_.isNull(item.employerId) ? '' : item.employerId.name}</td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>
        )
    }
}




export default withRouter(connect(mapStateToProps,mapDispatchToProps)(ListEmployee));

-----------
import React from 'react';
import {BrowserRouter, Route, Switch, withRouter} from "react-router-dom";
import ListEmployee from "./components/ListEmployee/ListEmployee";
import NotFound from "./components/NotFound";
import Navigate from "./components/Navigate/Navigate";
import {SERVER_API_CONNECT} from "./core/Constant";
import {connect} from "react-redux";
import {mapStateToProps} from "./store/stateToProps";
import {mapDispatchToProps} from "./store/dispatchToProps";


class App extends React.Component{

    render() {
        return (
            <BrowserRouter>
                <div className="container">
                    <Navigate/>
                    <Switch>
                        <Route path="/form_create"/>
                        <Route path="/list_employee" component={()=><ListEmployee/>}/>
                        <Route path="/list_organization"/>
                        <Route path="/tree_employee"/>
                        <Route path="/tree_organization"/>
                        <Route path="*" component={() => <NotFound/>}/>
                    </Switch>
                </div>
            </BrowserRouter>
        );
    }
}


export default connect(mapStateToProps,mapDispatchToProps)(App);


export function employeesFetchDataAction(url,search) {
    return (dispatch)=>{
        fetch(`${url}${search}`)
            .then(response=>{
                if(!response.ok){
                    throw new Error(response.statusText)
                }
                return response
            })
            .then(response=>response.json())
            .then(employees=>dispatch({ type:"INFO_FETCH_DATA_S", employees:employees}))
            .catch(()=>{})
    }
}


import {initialState} from "../store/initialState";

export function employeesReducer (state = initialState.listEmployees.employees, action) {
    switch (action.type) {
        case "INFO_FETCH_DATA_S":
            return action.employees
        default:
            return state;
    }
}


export const initialState = {
    listEmployees:{
        isLoading:false,
        employees:[],
        sort:"asc",
        sortField:"id",
        currentPage:0,
        search:"",
    },
    addNewEmployer:{
        name:"",
        organizationName:"",
        isEmployer:true
    },
}


import {employeesFetchDataAction} from "../actions/employeesFetchDataAction";
import {setSearchEmployeesAction} from "../actions/setSearchEmployeesAction";

export const mapDispatchToProps = dispatch => {
    return {
        getFetchData: (url,search)=>{dispatch(employeesFetchDataAction(url,search))},
        setSearchEmployees: (search)=>{dispatch(setSearchEmployeesAction(search))}
    }
}


export const mapStateToProps = state =>{
    return {
        listEmployees:{
            employees:state.listEmployees_employees,
            isLoading:false,
            sort:"asc",
            sortField:"id",
            currentPage:0,
            search:state.listEmployees_search,
        },
        addNewEmployer:{
            name:"",
            organizationName:"",
            isEmployer:true
        },
    }
}


import {combineReducers} from "redux";
import {employeesReducer} from "./employeesReducer";
import {setSearchEmployeesReducer} from "./setSearchEmployeesReducer";



const indexReducer = combineReducers({
    listEmployees_employees:employeesReducer,
    listEmployees_search:setSearchEmployeesReducer

});


export default indexReducer
  • Вопрос задан
  • 483 просмотра
Пригласить эксперта
Ответы на вопрос 1
@rew232edewqe Автор вопроса
Нашел ответ, переместив в componentDidMount получение данных.
А в App убрал connect.
Только вот вопрос как написать в одном action несколько изменений стейта за раз.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы