【问题标题】:Infinite loop while using useState() React.js使用 useState() React.js 时的无限循环
【发布时间】:2021-07-06 11:14:14
【问题描述】:
    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

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

【问题讨论】:

  • 您在 App 函数内直接调用 matchesCtx.addMatch({ ... })。你不应该那样做。要做到这一点,当应用程序安装时,将其包装在useEffect(() =&gt; {}, []) 中(添加会导致重新渲染,这会导致添加,这会导致重新渲染,这会导致添加等等。 )
  • 你向我澄清了一切,非常感谢:)

标签: javascript reactjs loops use-state


【解决方案1】:

应该是 `setStateMatches([...setMatches, stateMatches])

而不是 setStateMatches([...stateMatches, match]);

【讨论】:

  • 没有。什么是setMatches...? OP的setter代码很好,他们只是在错误的地方调用它。
猜你喜欢
  • 2021-08-11
  • 2021-11-11
  • 1970-01-01
  • 2021-03-31
  • 1970-01-01
  • 2020-02-21
  • 2021-08-28
  • 2020-12-04
  • 2021-05-17
相关资源
最近更新 更多