简体   繁体   中英

Infinite loop while using useState() React.js

    import { createContext, useState } from "react";
import React from "react";

const MatchesContext = createContext([]);

export function MatchesContextProvider(props) {

    const [stateMatches, setStateMatches] = useState([]);


    function addMatchHandler(match) {

        setStateMatches([...stateMatches, match]);

    }


    const context = {

        matches: stateMatches,
        addMatch: addMatchHandler

    };



    return <MatchesContext.Provider value={context}>

        {props.children}

    </MatchesContext.Provider>

}


export default MatchesContext;


That's my context

Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

And this is the error i get on this line:

    setStateMatches([...stateMatches, match]);

    import React from "react";
import Header from "./layout/Header";
import MatchTable from "./components/MatchTable";
import FormMatches from "./pages/FormMatches";

import Container from 'react-bootstrap/Container';
import { Route, Switch } from 'react-router-dom';

import { useContext } from "react";
import MatchesContext from "./store/MatchesContext";


function App() {

  const matchesCtx = useContext(MatchesContext);

  matchesCtx.addMatch({

    id: 4,
    team: "Newcastle",
    p: 38,
    w: 21,
    l: 8,
    d: 9,
    f: 74,
    a: 52,
    pts: 71

});

console.log(matchesCtx);

  return (

    <div>

      <Header />

      <Switch>

        <Route path='/input' exact>

          <FormMatches/>

        </Route>

        <Route path='/' exact>

          <Container>

            <MatchTable value={matchesCtx}/>

          </Container>

        </Route>

      </Switch>

    </div>

  );
}

export default App;

That's the App.js

    import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import 'bootstrap/dist/css/bootstrap.min.css';

import { BrowserRouter } from 'react-router-dom';
import { MatchesContextProvider } from './store/MatchesContext'

ReactDOM.render(
  <MatchesContextProvider>
  <BrowserRouter>
    <App />
  </BrowserRouter>
  </MatchesContextProvider>,
  document.getElementById('root')
);

index.js

I can't add an object to the array cause everytime i call the function i get that error, i didn't find any answer searching online just similar problems that didn't helped me at all.

Instead of setStateMatches([...stateMatches, match]); it should be `setStateMatches([...setMatches, stateMatches])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM