[英]Why does this component render twice?
export const AppComponent =()=>{
console.log('rendered');
const parameter = 'apple:two,mango:three'
.split(',')
.reduce((accumulator, currentValue) => {
const [key, value] = currentValue.split(':');
accumulator[key] = value;
}, {});
return <div/>
}
此組件呈現兩次並引發錯誤。 我知道錯誤是由於它們在 reduce 函數中沒有 return 語句。 但是我不明白的是為什么它渲染兩次?
此外,當我刪除accumulator[key] = value
代碼時,它只呈現一次。 據我了解,一個組件只能在四種情況下重新渲染
在我的情況下,父組件不會重新渲染(我通過在父組件中使用 console.log 檢查了它)並且該組件是無狀態的,並且沒有傳遞給它的道具。 有人可以解釋這種行為嗎?
問題在於您的 reduce 方法,您沒有返回累加器..
const App=()=> {
console.log("rendered");
const parameter = 'apple:two,mango:three'
.split(',')
.reduce((accumulator, currentValue) => {
const [key, value] = currentValue.split(':');
accumulator[key] = value;
return accumulator; // this line should fix
}, {});
return(<div>hello</div>);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.