如何根据react native中的状态值设置道具内部的条件



我使用组件<MapboxGL.UserLocation来获取当前用户坐标,在这个组件中有一个道具onUpdate,它可以获取用户的当前位置并将其传递给函数,我想要的是在调用道具内部的函数之前,检查状态值是真是假,只有当状态值为真时,函数才会被触发,我已经做了以下操作,但它总是调用函数onUserLocationUpdate(location),即使状态为假

<MapboxGL.UserLocation
renderMode="normal"
visible={true}
onUpdate={location => {
if (!isStartL) {
console.log("not start yet")
} else {
onUserLocationUpdate(location)
}
}}
/>

这是我使用const [isStartL, setisStartL] = useState(false);的状态

更新完整代码:

const app = ({ navigation }) => {
const [isStartL, setisStartL] = useState(false);
const onUserLocationUpdate = (location) => {
console.log(location);
}
const renderLocationInfo = () => {

if (!isStartL) {
return (<View style={styles.rcontainer}>
<Text style={styles.btn}>Press start when you are in the same location </Text>
<TouchableOpacity onPress={setisStartL(true)} >Start</TouchableOpacity>
</View>)
}
}
return (
<View style={styles.matchParent}>
<MapboxGL.MapView

surfaceView={true}
zoomLevel={15}
logoEnabled={false}
style={styles.matchParent}
>
<MapboxGL.UserLocation
renderMode="normal"
visible={true}
onUpdate={(location) => {
(!isStartL) ? console.log("not start yet") : onUserLocationUpdate(location)
}}
/>
<MapboxGL.Camera
followZoomLevel={17} 
followUserMode={'normal'}
followUserLocation={true}
followZoomLevel={17}
animationDuration={1000}
/>
</MapboxGL.MapView>
{renderLocationInfo()}
</View>
)
}

执行以下操作:

<MapboxGL.UserLocation
renderMode="normal"
visible={true}
onUpdate={(location) => {
(!isStartL) ? console.log("not start yet") : onUserLocationUpdate(location)
}}
/>

尝试这种方式

<MapboxGL.UserLocation
renderMode="normal"
visible={true}
onUpdate={(location) => {
isStartL
? onUserLocationUpdate(location)
: console.log('not start yet');
}}
/>

一种方法是将if逻辑移动到onUserLocationUpdate()函数内部。

如果您的状态为false,请从中返回。否则,请执行其他步骤。

通过这种方式,您可以确保预期的行为。

最新更新