首页 > 解决方案 > 使用 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

错误:超过最大更新深度。当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况。React 限制了嵌套更新的数量以防止无限循环。

这是我在这条线上得到的错误:

    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;

这就是 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

我无法将对象添加到数组中,因为每次我调用该函数时都会收到该错误,我没有找到任何答案在线搜索只是类似的问题根本没有帮助我。

标签: javascriptreactjsloopsuse-state

解决方案


而不是setStateMatches([...stateMatches, match]);应该是 `setStateMatches([...setMatches, stateMatches])


推荐阅读