javascript - 使用 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
我无法将对象添加到数组中,因为每次我调用该函数时都会收到该错误,我没有找到任何答案在线搜索只是类似的问题根本没有帮助我。
解决方案
而不是setStateMatches([...stateMatches, match]);
应该是 `setStateMatches([...setMatches, stateMatches])
推荐阅读
- angular - 如何在primeNg中单击分页器更改事件时更改p表的行索引数
- python - 如何使用内部键:值对将字典列表转换为字典字典
- flutter - Flutter:未来的构建者不更新表单值
- python - 使用 pandas 从列中查找字符串
- reactjs - 映射嵌套在来自 API 的对象中的对象 | JSX 映射问题
- jquery - Ajax post 调用多次
- python - 为什么亚马逊 S3 客户端依赖于位置?
- node.js - PM2 无法获取 ~/.profile 文件中设置的更新值
- python - 基于 cumsum 从轮廓填充区域
- unit-testing - 使用 DI (injectable-getIt) 进行颤振测试的正确方法?