[英]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.
当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,就会发生这种情况。 React limits the number of nested updates to prevent infinite loops.
React 限制嵌套更新的数量以防止无限循环。
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这就是 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索引.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]);
而不是
setStateMatches([...stateMatches, match]);
it should be `setStateMatches([...setMatches, stateMatches])它应该是`setStateMatches([...setMatches, stateMatches])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.