首页 > 解决方案 > 如何在本机反应中根据状态值在道具内设置条件?

问题描述

我正在使用组件<MapboxGL.UserLocation来获取当前用户坐标,并且在这个组件中有一个道具onUpdate可以获取用户的当前位置并将其传递给一个函数,我想要的是在调用道具内的函数之前检查状态值是否是true 或 false 并且仅当状态值为 true 时才会触发函数,我已经完成了以下操作,但onUserLocationUpdate(location)即使状态为 false ,它也会始终调用函数

<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>
)
}

标签: javascriptreact-nativereact-propsuse-state

解决方案


请执行下列操作:

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

推荐阅读