R
R
rew232edewqe2019-03-06 22:54:38
React
rew232edewqe, 2019-03-06 22:54:38

How to fix Redux infinite refresh?

The essence of the question is that when I use it in componentDidMount in the App, everything normally loads the data once, but for some reason, when entering into the search field, the target gets lost from the field.
And also (below the code is presented), when I use in componentDidMount in ListEmployee with the same request, it endlessly sends requests. As I understand it, the ListEmployee class is updated endlessly using Route?
I would be grateful for your help =). With this editor, everything is somehow confusing.
Maybe someone else can tell you which way to go.

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

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
rew232edewqe, 2019-03-07
@rew232edewqe

Found the answer by moving the data receiving to componentDidMount .
And in App removed connect.
Only here is the question of how to write several state changes at a time in one action.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question