ใช้ React.memo ในส่วนประกอบที่ใช้งานได้เพื่อ renderItem FlatList เพื่อลดการแสดงรายการที่มีอยู่ซ้ำให้น้อยที่สุด
ฉันใช้ส่วนประกอบที่ใช้งานได้และใช้ Flatlist เพื่อแสดงรายการข้อมูลมันใช้งานได้ แต่ทุกครั้งที่รัฐได้รับข้อมูลเพิ่มเติมมันจะแสดงผลที่มีอยู่เสมอและจะทำให้เกิดปัญหาด้านประสิทธิภาพฉันได้อ่านบทความเหล่านี้จาก SO แต่ก็ยังมี ไม่มีเบาะแส
- https://stackoverflow.com/a/57405307/938947
- https://stackoverflow.com/a/46349156/938947
นี่คือรหัสของฉันที่ใช้ Flatlist หลัก
<FlatList
horizontal={false}
showsHorizontalScrollIndicator={false}
data={users}
keyExtractor={(item, index) => String(index)}
renderItem={RenderUser}
onEndReachedThreshold={0.7}
onEndReached={callBackMoreData}
/>
และนี่คือ RenderUser ที่ใช้งานได้ แต่ปัญหาในการแสดงรายการที่มีอยู่หากสถานะมีข้อมูลเพิ่มเติมสิ่งที่ฉันต้องการจะบรรลุคือการแสดงข้อมูลเพิ่มเติมเท่านั้น
import React from 'react';
import { ListItem } from 'react-native-elements';
const RenderUser = ({ item, index }) => {
return (
<React.Fragment>
{ console.log('index: ', index)}
<ListItem
title={item.attributes.name}
/>
</React.Fragment>
);
};
export default RenderUser;
และฉันได้ลองใช้รหัสนี้ด้านล่าง (แต่ฉันได้รับข้อความแสดงข้อผิดพลาดว่า TypeError: renderItem ไม่ใช่ฟังก์ชัน (ใน 'renderItem (props)', 'renderItem' เป็นตัวอย่างของวัตถุ))
import React, { memo } from 'react';
import { ListItem } from 'react-native-elements';
const RenderUser = ({ item, index }) => {
return (
<React.Fragment>
{ console.log('index: ', index)}
<ListItem
title={item.attributes.name}
/>
</React.Fragment>
);
};
export default memo(RenderUser);
คำตอบ
ตามเอกสารทางการตอบสนอง:
โดยค่าเริ่มต้นจะเปรียบเทียบวัตถุที่ซับซ้อนในวัตถุประกอบฉากอย่างตื้น ๆ เท่านั้น หากคุณต้องการควบคุมการเปรียบเทียบคุณยังสามารถให้ฟังก์ชันการเปรียบเทียบแบบกำหนดเองเป็นอาร์กิวเมนต์ที่สองได้
function MyComponent(props) {
/* render using props */
}
function areEqual(prevProps, nextProps) {
/*
return true if passing nextProps to render would return
the same result as passing prevProps to render,
otherwise return false
*/
}
export default React.memo(MyComponent, areEqual);
ในกรณีของคุณคุณต้องเพิ่มเงื่อนไข:
import React, { memo } from 'react';
import { ListItem } from 'react-native-elements';
const RenderUser = ({ item, index }) => {
return (
<React.Fragment>
{ console.log('index: ', index)}
<ListItem
title={item.attributes.name}
/>
</React.Fragment>
);
};
function arePropsEqual(prevProps, nextProps) {
/*
return true if passing nextProps to render would return
the same result as passing prevProps to render,
otherwise return false
*/
return nextProps.item.attribute.name===prevProps.item.attribute.name
}
export default memo(RenderUser,arePropsEqual);
หมายเหตุ : ไม่แน่ใจว่าคุณได้รับอุปกรณ์ประกอบฉากจำนวนเท่าใดและมีอะไรที่ไม่เหมือนใคร โดยทั่วไปคุณต้องเปรียบเทียบว่าอันสุดท้ายมีค่าเท่ากับค่านี้ส่งคืนจริงในลักษณะนั้นการตอบสนองจะไม่ทำให้ส่วนประกอบของคุณกลับมาอีกครั้ง