我试图通过多个嵌套循环传递一个名为“clicker()”的函数。我收到以下错误:
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.
clicker()
函数遵循以下路径:
app.js --> one.js --> 二.js --> 三.js
如何传递这个在 app.js 中启动的函数,直到它到达最后一个组件。请注意,app.js
渲染 one
,这渲染 two
,这渲染 Three
。
here是我的codesandbox。
app.js
:
import React, { useState } from "react";
import One from "./components/one";
export default function App() {
const [counter, updateCounter] = useState(0);
let clicker = () => {
updateCounter(counter + 1);
};
return (
<div className="App">
<h1>how to pass a function through nested components in React </h1>
<h3> {counter} </h3>
<One passMe={clicker} />
</div>
);
}
和one.js
import Two from "./two";
function One(props) {
return (
<div className="App">
<p> this is the nested function</p>
<Two passMe={props.passMe} />
</div>
);
}
export default One;
和two.js
import React from "react";
import Three from './three'
export default function Two(props) {
return (
<div className="App">
<Three passMe={props.passMe} />
</div>
);
}
最后是two.js
import React from "react";
export default function App(props) {
return (
<div >
<button passMe={props.passMe(5)}>Cliicker! </button>
</div>
);
}
非常感谢
最佳答案
如果函数不支持任何参数,为什么要传递 5 作为参数?
假设您想要这样,您可以更改此设置:
在App.js上:
const clicker = (num = 1) => {
updateCounter(counter + num);
};
在三.js上:
<button onClick={() => props.passMe(5)}>Cliicker!</button>
关于javascript - 如何在react中通过多个嵌套循环传递函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70809561/