与三元运算符反应条件渲染

时间:2020-09-02 14:20:13

标签: javascript reactjs

首次加载屏幕时,我正在从服务器获取一些信息并设置状态。如果用户使用选择菜单并选择其他选项,则会更改状态。

因此,我基本上是想说,如果状态值来自服务器,请显示出来,或者如果状态值来自用户选择,请使用该值。我还尝试使用&&首先确保甚至没有可用的值。

const [country, setCountry] = useState();

useEffect(() => {
   // get location via public IP lookup and set state of country c 
   //calling code based on IP eg: +44
   setCountry(countryInfo.data);
 }, []);

<Input
name="countryCode"
placeholder={
country && country.location.calling_code ? country.location.calling_code : country.callingCode }
width="20%"
editable={false}
/>

<CountryPicker
  name="country"
  theme={{ fontSize: 14, padding: 30 }}
  countryCode={
    country && country.country_code
      ? country.country_code
      : country && country.cca2
  }
  withCallingCode
  withFilter
  withCountryNameButton={true}
  withFlagButton={false}
  withFlag={false}
  withEmoji={false}
  onSelect={(country) => setCountry(country)}
/>

country.location.calling_code是来自服务器的初始负载,country.callingCode是用户决定通过下拉菜单进行更改的情况。

我得到的错误是:

未定义不是对象(正在评估country.location.calling_code)

2 个答案:

答案 0 :(得分:1)

您可以先使用此丝束形状

country && country.location && country.location.calling_code ? country.location.calling_code : country.callingCode

或这个形状,它认为此形状适合打字稿

country?.location?.calling_code ? country.location.calling_code : country.callingCode

如果衡量了?该项目将移至该物业

答案 1 :(得分:0)

位置也可能不存在,因此请检查以确保存在。

country && country.location && country.location.calling_code ? country.location.calling_code : country && country.callingCode || ""

country?.location?.calling_code ? country.location.calling_code : country?.callingCode || ""