[英]Unbale to prevent re rendering using useCallback and React.memo
I am using React Native version 0.64.我正在使用 React Native 0.64 版。 I have a page which consist of one mapview and two buttons.
我有一个包含一个地图视图和两个按钮的页面。 using that two buttons I am updating the state, but whenever I am updating the state the map component is getting re-rendered.
使用这两个按钮我正在更新状态,但是每当我更新状态时,地图组件都会重新渲染。 To prevent re-rendering I have used
React.memo
and React.useCallback
, but it seems to re-rendering the map component.为了防止重新渲染,我使用了
React.memo
和React.useCallback
,但它似乎重新渲染了地图组件。
Here is the code:-这是代码:-
import React from 'react'
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
import MapView, { PROVIDER_GOOGLE, Marker } from 'react-native-maps';
const PilgrimTracker = () => {
const [index, setIndex] = React.useState(0)
const lost = React.useCallback((value) => { setIndex(value) }, [index])
const MapComponent = React.memo(()=> {
console.log('render')
return (
<MapView
provider={PROVIDER_GOOGLE}
style={{ flex: 1 }}
region={{
latitude: 22.57687,
longitude: 88.35047,
latitudeDelta: 0.015,
longitudeDelta: 0.0121,
}}
>
<Marker coordinate={{ latitude: 22.57687, longitude: 88.35047 }} />
</MapView>
)
})
return (
<View style={styles.container}>
<MapComponent />
<TouchableOpacity
onPress={()=>lost(0)} style={{ flex: 1, justifyContent: 'center', alignItems: 'center',backgroundColor:'green' }}>
<Text>Yes, I’m Lost</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={()=>lost(1)} style={{ flex: 1, justifyContent: 'center', alignItems: 'center',backgroundColor:'blue' }}>
<Text>Other member Lost</Text>
</TouchableOpacity>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1
}
})
export default PilgrimTracker
How should I stop the re-rendering?我应该如何停止重新渲染?
try this code.试试这个代码。 it working ;
它工作;
const Parent = () => {
const [childAState, setChildAState] = useState();
useEffect(() => {
setChildAState('Child A Updated');
}, []);
return (
<>
<ChildA childAState={childAState}/>
<ChildB />
</>
);
};
const ChildA = () => React.memo((props) => {
return <h1>Child A</h1>
});
const ChildB = () => React.memo((props) => {
return <h1>Child B</h1>
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.