默认值首先是useState



我使用react-native-phone-number-input来获取用户的电话号码。还使用博览会位置获取用户的isoCountryCode,然后我将其设置为useState变量,但在开始时它为null,因此在电话号码部分出现默认值,我如何才能正确捕获它?

import PhoneInput, { PhoneInputProps } from 'react-native-phone-number-input';
import * as Location from 'expo-location';
const [countryCode, setCountryCode] = useState<
    PhoneInputProps['defaultCode'] | string | null
  >();
  useEffect(() => {
    (async () => {
      const { status } = await Location.requestForegroundPermissionsAsync();
      if (status !== 'granted') {
        setCountryCode('GB');
        return;
      }
      const location = await Location.getCurrentPositionAsync({});
      // await Location.isBackgroundLocationAvailableAsync()
      await (
        await Location.reverseGeocodeAsync(location.coords)
      ).map((a) => setCountryCode(a.isoCountryCode)); <<< I catch the isoCountryCode here
    })();
  }, []);
  console.log('Country Code : ', countryCode);
...
<PhoneInput
      ref={childRef}
      value={value}
      defaultCode={countryCode ? countryCode : 'GB'} <<< It should be set here, but always default comes first
      textInputProps={{
        keyboardType: 'phone-pad',
        ...(props.textInputProps || {}),
      }}
      containerStyle={{ marginTop: 20, backgroundColor: 'transparent' }}
      countryPickerButtonStyle={styles.countryPickerButtonStyle}
      textContainerStyle={styles.textContainer}
      flagButtonStyle={{}}
      textInputStyle={{}}
      codeTextStyle={{}}
      countryPickerProps={{
        ...(props.countryPickerProps || {}),
      }}
...

和console.log输出

Country Code :  undefined
Country Code :  TR

您的状态默认值为undefined, useEffect中的代码为async。因此,预计在第一次渲染中状态的值为undefined。在useEffect中设置新状态后,将使用更新后的状态值运行新的呈现周期。

如果你想防止这种情况发生,你可以提供一个默认值(如果我们在这里讨论位置,这可能没有多大意义)

const [countryCode, setCountryCode] = useState<
    PhoneInputProps['defaultCode'] | string | null
  >(‘SomeCode’);

或者您可以使用条件渲染等待,直到获取位置,如下所示。


const [countryCode, setCountryCode] = useState<
    PhoneInputProps['defaultCode'] | string | null
  >();
  useEffect(() => {
    (async () => {
      const { status } = await Location.requestForegroundPermissionsAsync();
      if (status !== 'granted') {
        setCountryCode('GB');
        return;
      }
      const location = await Location.getCurrentPositionAsync({});
      // await Location.isBackgroundLocationAvailableAsync()
      await (
        await Location.reverseGeocodeAsync(location.coords)
      ).map((a) => setCountryCode(a.isoCountryCode)); <<< I catch the isoCountryCode here
    })();
  }, []);
if (!countryCode) {
   return null
}
// else return phone input 
return (…)

最新更新