我試圖通過多個嵌套回圈傳遞一個名為“clicker()”的函式。我收到以下錯誤:
超過最大更新深度。當組件在 componentWillUpdate 或 componentDidUpdate 中重復呼叫 setState 時,可能會發生這種情況。React 限制了嵌套更新的數量以防止無限回圈。
該clicker()函式遵循以下路徑:
app.js --> one.js --> two.js --> three.js
我怎樣才能傳遞這個在 app.js 中一直啟動的函式,直到它到達最后一個組件。請注意,app.jsrendersone和 this renderstwo和 this renders three。
這是我的密碼箱。
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>
);
}
最后 three.js
import React from "react";
export default function App(props) {
return (
<div >
<button passMe={props.passMe(5)}>Cliicker! </button>
</div>
);
}
非常感謝
uj5u.com熱心網友回復:
如果函式不支持,為什么要傳遞 5 作為引數?
假設你想要這樣,你可以改變這個:
在App.js 上:
const clicker = (num = 1) => {
updateCounter(counter num);
};
在三個.js 上:
<button onClick={() => props.passMe(5)}>Cliicker!</button>
uj5u.com熱心網友回復:
實際上,您將函式從父組件傳遞到其嵌套的子組件是正確的。但是假設您想在用戶單擊其嵌套組件上的按鈕時更新計數器,您可能需要傳遞onClick(()=> props.passMe(anyValue))on three.jsbutton 組件。這樣,在從three.js, two.js,one.js到的每個按鈕單擊時都會呼叫在父級中創建的函式app.js。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/418836.html
標籤:
上一篇:如何使我的頭檔案、函式和主檔案一起作業,我總是得到:錯誤:ID回傳1退出狀態
下一篇:功能不起作用,說它沒有定義?
