我有那個組件:
<SelectCampanha
titulo="Preenchimento obrigatório"
listaOpcoes={
category
? riskModel.filter((item) =>
item.CategoryType.includes(categoria)
)
: riskModel}
/>
現在我想將此過濾器傳遞給一個函式
const filter = () => {
return category
? riskModel.filter((item) =>
item.CategoryType.includes(categoria)
)
: riskModel
}
我想知道在 Props 傳遞中呼叫箭頭函式和函式之間的區別。
在組件中呼叫此函式的正確方法是什么?
<SelectCampanha
titulo="Preenchimento obrigatório"
listaOpcoes={filter()}
/>
要么
<SelectCampanha
titulo="Preenchimento obrigatório"
listaOpcoes={() => filter()}
/>
當我使用最后一個選項時,它似乎運行了一次函式并且沒有時間更新變數的狀態
uj5u.com熱心網友回復:
傳遞函式與傳遞其回傳值不同。
當你通過filter()時,它會被呼叫并回傳值將被傳遞。
或者,如果您傳遞() => filter()它與傳遞相同filter- 然后您傳遞實際的function。當您想要將計算與傳入函式的背景關系分離時,這很有用。
在您的情況下,您似乎想將計算包裝在filter函式中,因此您需要filter()作為道具傳遞 - 因為您將其結果用作實際道具。
uj5u.com熱心網友回復:
如果要傳遞過濾的專案,則取決于您的道具的期望,您應該避免使用箭頭功能并使用
<SelectCampanha
titulo="Preenchimento obrigatório"
listaOpcoes={filter()}
/>
uj5u.com熱心網友回復:
我想知道在 Props 傳遞中呼叫箭頭函式和函式之間的區別。
在 Javascript 中,當出現時呼叫一個函式functionName()(注意())。通常,您希望將函式傳遞給組件以便稍后呼叫它(例如作為組件內部的單擊處理程式),而不是將return value函式的傳遞給組件。
function myMethod() {
return 1
}
<MyComponent myPassedMethod={myMethod} myPassedValue={myMethod()} />
在給定的示例中,propsofMyComponent將是這樣的:
{
myPassedMethod: // function definition of "myMethod"
myPassedValue: 1 //return value of "myMethod"
}
因此,當您像這樣傳遞過濾器方法時:
listaOpcoes={filter()}
你會通過return value的filter()。
如果你像這樣通過它:
listaOpcoes={() => filter()}
afunction被傳遞給組件 props,稍后可以在組件內部呼叫。
也許這個兩個等價運算式的例子也能澄清一點:
listaOpcoes={filter()}相當于listaOpcoes={() => { return filter()}()}
uj5u.com熱心網友回復:
沒有正確的傳遞道具的方法。雖然這兩個選項都是正確的。這取決于你想如何解釋你通過的道具。
第一個選項
您呼叫過濾器函式并將函式的回傳值作為道具傳遞給SelectCampanha組件。
例如,要在SelectCampanha組件中使用 prop(使用第一個選項傳遞 prop):
export function SelectCampanha({ listaOpcoes }) {
// listaOpcoes is an array!
listaOpcoes.map(item => ...)
}
第二種選擇
您傳遞一個匿名函式,該函式將過濾器函式的回傳值作為道具回傳給SelectCampanha組件。
例如,要在SelectCampanha組件中使用 prop(使用第二個選項傳遞 prop):
export function SelectCampanha({ listaOpcoes }) {
// listaOpcoes is a function!
// Firstly, we call the function to get the returned array
const data = listaOpcoes()
// data is an array returned from the filter() function
data.map(item => ...)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/432882.html
標籤:javascript 反应 功能 箭头函数
